问:
PickerView Keyboard & Tap to Dismiss SwiftUI

Xcode 11.2.1, Swift 5.0

I want to try and replicate this feature that Apple has in their health app:

The feature includes a couple of things:

PickerView presented sort of like a keyboard on tap.

PickerView is dismissed on tap outside.

So far, I have tried to get things very similar to this up and running. For example, I was trying to get an alert with a custom body (that would fill the whole screen)  that you could call from any view working, but I found it challenging for a number of reasons, including but not limited by: being restricted to positioning a view in its own local coordinate system, not being able to add a view on top of all other views in SwiftUI's layout system, etc. The keyboard-like presentation style of the picker makes it tricky to lay it out on top of everything else, similar to the alert. With respect to the feature of dismissing on tap outside, I have also tried to implement this in some capacity with no success. The ideal way to do this would be to add a gesture recognizer of sorts in front of everything but the child view (in my experiments with this, I was trying to add this for a TextField). This proved to be a challenging task as, as mentioned previously, it is very tricky to lay things out in the global coordinate system irrespective of the child you are laying it out from. I thought that maybe some way of navigating through the view hierarchy from the child view may do the trick, but I am not sure how to do this (may preference keys or environment variables, I'm not sure), don't if this would work at all, and don't know if something that meets this specification to meaningful level really even exists in SwiftUI. I suspect that interfacing with UIKit will probably be the only solution but I am not sure how to properly do this for this feature.

My Current Attempt

struct ContentView: View {
    @State var present = false
    @State var date = Date()

    var formattedDate: String {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        return formatter.string(from: date)
    }

    var body: some View {
        VStack {

            HStack {
                Rectangle()
                    .fill(Color.green)
                    .cornerRadius(15)
                    .frame(width: 100, height: 100)

                Rectangle()
                    .fill(Color.red)
                    .cornerRadius(15)
                    .frame(height: 100)
                    .overlay(Text(formattedDate).foregroundColor(.white))
                    .shadow(radius: 10)
                    .onTapGesture { self.present.toggle() }
                    .padding(20)
                    .alert(isPresented: $present, contents: {

                        VStack {
                            Spacer()
                            HStack {
                                Spacer()
                                DatePicker(selection: self.$date, displayedComponents: .date) { EmptyView() }
                                    .labelsHidden()
                                Spacer()
                            }
                            .padding(.bottom, 20)
                            .background(BlurView(style: .light).blendMode(.plusLighter))

                        }
                    }) {
                        withAnimation(.easeInOut) {
                            self.present = false
                        }
                }
            }
        }

    }
}

struct BlurView: UIViewRepresentable {

    typealias UIViewType = UIVisualEffectView

    let style: UIBlurEffect.Style

    func makeUIView(context: Context) -> UIViewType {
        let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: style))
        return visualEffectView
    }

    func updateUIView(_ uiView: UIViewType, context: Context) { }
}

extension View {

func alert<Contents: View>(isPresented: Binding<Bool>, contents: @escaping () -> Contents, onBackgroundTapped: @escaping () -> Void = { }) -> some View {

    self.modifier(AlertView(isPresented: isPresented, contents: contents, onBackgroundTapped: onBackgroundTapped))
    }
}

struct AlertView<Contents: View>: ViewModifier {
    @Binding var isPresented: Bool
    var contents: () -> Contents
    var onBackgroundTapped: () -> Void = { }

    @State private var rect: CGRect = .zero

    func body(content: Content) -> some View {
        if rect == .zero {
            return AnyView(
                content.bindingFrame(to: $rect))
        } else {
            return AnyView(content
                .frame(width: rect.width, height: rect.height)
                .overlay(
                    ZStack(alignment: .center) {
                        Color
                            .black
                            .opacity(isPresented ? 0.7 : 0)
                            .edgesIgnoringSafeArea(.all)
                            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
                            .position(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY, in: .global)
                            .onTapGesture {
                                self.onBackgroundTapped()
                            }
                            .animation(.easeInOut)

                        contents()
                            .position(x: UIScreen.main.bounds.midX, y: isPresented ? UIScreen.main.bounds.midY : (UIScreen.main.bounds.midY + UIScreen.main.bounds.height), in: .global)
                            .animation(.spring())
                    }
                    .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height),
                    alignment: .center))
        }

    }
}

public extension View {
    func position(_ position: CGPoint, in coordinateSpace: CoordinateSpace) -> some View {
        return self.position(x: position.x, y: position.y, in: coordinateSpace)
    }
    func position(x: CGFloat, y: CGFloat, in coordinateSpace: CoordinateSpace) -> some View {
        GeometryReader { geometry in
            self.position(x: x - geometry.frame(in: coordinateSpace).origin.x, y: y - geometry.frame(in: coordinateSpace).origin.y)
        }
    }
}

struct GeometryGetter: View {
    @Binding var rect: CGRect

    var body: some View {
        return GeometryReader { geometry in
            self.makeView(geometry: geometry)
        }
    }

    func makeView(geometry: GeometryProxy) -> some View {
        DispatchQueue.main.async {
            self.rect = geometry.frame(in: .global)
        }

        return Rectangle().fill(Color.clear)
    }
}

extension View {
    func bindingFrame(to binding: Binding<CGRect>) -> some View {
        self.background(GeometryGetter(rect: binding))
    }
}

```

Problems:

Since the animation can't really know that the view only takes up the bottom part of the screen, it makes it build out way too quickly because the final distance is further.

I cannot use the safe area of the device to pad my view, so I just end up guessing to pad it by 20 on the bottom, but that is not a very scalable solution.

I do not this will scale up very well. Quite frankly, this feels like a bit of a hacky solution as we don't really want to layout the view in the child's bounds, but we are sort of forced to do so. Moreover, you run into problems immediately if the child view this is being called on is not at the highest z-index position on the screen, as other items will obstruct it and the alert (picker pop-up).

Note: I'm sure there are more issues with it than I mentioned I just have not been able to think of them at the moment, and anyways, those are some of the primary issues.

How can I replicate these effectively features in SwiftUI? I would like to be able to activate this from a child view (like a child view in a separate file, not the root view).

Note: Interfacing with UIKit is a totally acceptable solution as long as it is only an implementation detail and acts as a regular SwiftUI view does for the most part.

Thank you!

答:
I was trying to do something similar to this. Here is a half-finished solution (no Geometry Reader to push up the screen, and not using BlurView).

For me, the critical stumbling block was using the mask on the TapGesture, otherwise my onTapGesture's that I previously used swallowed all Form taps.

```<code>struct BottomSheetPicker: View {
    @Binding var selection: Double

    var min: Double = 0.0
    let max: Double
    var by: Double = 1.0
    var format: String = "%d"

    var body: some View {
        Group {
            Picker("", selection: $selection) {
                ForEach(Array(stride(from: min, through: max, by: by)), id: \.self) { item in
                    Text(String(format: self.format, item))
                }
            }
            .pickerStyle(WheelPickerStyle())
            .foregroundColor(.white)
            .frame(height: 180)
            .padding()
        }.background(Color.gray)
    }
}
</code>```

And here is the main content view:

```<code>struct MyContentView: View {
    @State private var heightCm = 0.0
    @State private var weightKg = 0.0

    @State private var pickerType = 0 // TODO: Update to Enum
    private var isShowingOverlay: Bool {
        get {
            return self.pickerType != 0
        }
    }

    private let heightFormat = "%.0f cm"
    private let weightFormat = "%.1f kg"

    private var heightPicker: some View {
        BottomSheetPicker(selection: $heightCm, max: 300, format: heightFormat)
    }

    private var weightPicker: some View {
        BottomSheetPicker(selection: $weightKg, max: 200, by: 0.5, format: weightFormat)
    }

    // There are a few nicer ways to do this, just wanted to whip up a quick demo
    private var pickerOverlay: some View {
        Group {
            if pickerType == 1 {
                heightPicker
            } else if pickerType == 2 {
                weightPicker
            } else {
                EmptyView()
            }
        }
    }

    var body: some View {
        ZStack {
            Form {
                Section(header: Text("Personal Information")) {
                    HStack {
                        Text("Height")
                        Spacer()
                        Text(String(format: heightFormat, self.heightCm))
                    }
                    .contentShape(Rectangle())
                    .onTapGesture {
                        self.pickerType = 1
                    }

                    HStack {
                        Text("Weight")
                        Spacer()
                        Text(String(format: weightFormat, self.weightKg))
                    }
                    .contentShape(Rectangle())
                    .onTapGesture {
                        self.pickerType = 2
                    }
                }
            }
            .gesture(TapGesture().onEnded({
                self.pickerType = 0
            }), including: isShowingOverlay ? .all : .none)

            if isShowingOverlay {
                pickerOverlay
                    .frame(alignment: .bottom)
                    .transition(AnyTransition.move(edge: .bottom))
                    .animation(.easeInOut(duration: 0.5))
            }
        }
    }
}
</code>```

Body:
Xcode 11.2.1, Swift 5.0

I want to try and replicate this feature that Apple has in their health app:

The feature includes a couple of things:

PickerView presented sort of like a keyboard on tap.

PickerView is dismissed on tap outside.

So far, I have tried to get things very similar to this up and running. For example, I was trying to get an alert with a custom body (that would fill the whole screen)  that you could call from any view working, but I found it challenging for a number of reasons, including but not limited by: being restricted to positioning a view in its own local coordinate system, not being able to add a view on top of all other views in SwiftUI's layout system, etc. The keyboard-like presentation style of the picker makes it tricky to lay it out on top of everything else, similar to the alert. With respect to the feature of dismissing on tap outside, I have also tried to implement this in some capacity with no success. The ideal way to do this would be to add a gesture recognizer of sorts in front of everything but the child view (in my experiments with this, I was trying to add this for a TextField). This proved to be a challenging task as, as mentioned previously, it is very tricky to lay things out in the global coordinate system irrespective of the child you are laying it out from. I thought that maybe some way of navigating through the view hierarchy from the child view may do the trick, but I am not sure how to do this (may preference keys or environment variables, I'm not sure), don't if this would work at all, and don't know if something that meets this specification to meaningful level really even exists in SwiftUI. I suspect that interfacing with UIKit will probably be the only solution but I am not sure how to properly do this for this feature.

My Current Attempt

struct ContentView: View {
    @State var present = false
    @State var date = Date()

    var formattedDate: String {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        return formatter.string(from: date)
    }

    var body: some View {
        VStack {

            HStack {
                Rectangle()
                    .fill(Color.green)
                    .cornerRadius(15)
                    .frame(width: 100, height: 100)

                Rectangle()
                    .fill(Color.red)
                    .cornerRadius(15)
                    .frame(height: 100)
                    .overlay(Text(formattedDate).foregroundColor(.white))
                    .shadow(radius: 10)
                    .onTapGesture { self.present.toggle() }
                    .padding(20)
                    .alert(isPresented: $present, contents: {

                        VStack {
                            Spacer()
                            HStack {
                                Spacer()
                                DatePicker(selection: self.$date, displayedComponents: .date) { EmptyView() }
                                    .labelsHidden()
                                Spacer()
                            }
                            .padding(.bottom, 20)
                            .background(BlurView(style: .light).blendMode(.plusLighter))

                        }
                    }) {
                        withAnimation(.easeInOut) {
                            self.present = false
                        }
                }
            }
        }

    }
}

struct BlurView: UIViewRepresentable {

    typealias UIViewType = UIVisualEffectView

    let style: UIBlurEffect.Style

    func makeUIView(context: Context) -> UIViewType {
        let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: style))
        return visualEffectView
    }

    func updateUIView(_ uiView: UIViewType, context: Context) { }
}

extension View {

func alert<Contents: View>(isPresented: Binding<Bool>, contents: @escaping () -> Contents, onBackgroundTapped: @escaping () -> Void = { }) -> some View {

    self.modifier(AlertView(isPresented: isPresented, contents: contents, onBackgroundTapped: onBackgroundTapped))
    }
}

struct AlertView<Contents: View>: ViewModifier {
    @Binding var isPresented: Bool
    var contents: () -> Contents
    var onBackgroundTapped: () -> Void = { }

    @State private var rect: CGRect = .zero

    func body(content: Content) -> some View {
        if rect == .zero {
            return AnyView(
                content.bindingFrame(to: $rect))
        } else {
            return AnyView(content
                .frame(width: rect.width, height: rect.height)
                .overlay(
                    ZStack(alignment: .center) {
                        Color
                            .black
                            .opacity(isPresented ? 0.7 : 0)
                            .edgesIgnoringSafeArea(.all)
                            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
                            .position(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY, in: .global)
                            .onTapGesture {
                                self.onBackgroundTapped()
                            }
                            .animation(.easeInOut)

                        contents()
                            .position(x: UIScreen.main.bounds.midX, y: isPresented ? UIScreen.main.bounds.midY : (UIScreen.main.bounds.midY + UIScreen.main.bounds.height), in: .global)
                            .animation(.spring())
                    }
                    .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height),
                    alignment: .center))
        }

    }
}

public extension View {
    func position(_ position: CGPoint, in coordinateSpace: CoordinateSpace) -> some View {
        return self.position(x: position.x, y: position.y, in: coordinateSpace)
    }
    func position(x: CGFloat, y: CGFloat, in coordinateSpace: CoordinateSpace) -> some View {
        GeometryReader { geometry in
            self.position(x: x - geometry.frame(in: coordinateSpace).origin.x, y: y - geometry.frame(in: coordinateSpace).origin.y)
        }
    }
}

struct GeometryGetter: View {
    @Binding var rect: CGRect

    var body: some View {
        return GeometryReader { geometry in
            self.makeView(geometry: geometry)
        }
    }

    func makeView(geometry: GeometryProxy) -> some View {
        DispatchQueue.main.async {
            self.rect = geometry.frame(in: .global)
        }

        return Rectangle().fill(Color.clear)
    }
}

extension View {
    func bindingFrame(to binding: Binding<CGRect>) -> some View {
        self.background(GeometryGetter(rect: binding))
    }
}

Problems:

Since the animation can't really know that the view only takes up the bottom part of the screen, it makes it build out way too quickly because the final distance is further.

I cannot use the safe area of the device to pad my view, so I just end up guessing to pad it by 20 on the bottom, but that is not a very scalable solution.

I do not this will scale up very well. Quite frankly, this feels like a bit of a hacky solution as we don't really want to layout the view in the child's bounds, but we are sort of forced to do so. Moreover, you run into problems immediately if the child view this is being called on is not at the highest z-index position on the screen, as other items will obstruct it and the alert (picker pop-up).

Note: I'm sure there are more issues with it than I mentioned I just have not been able to think of them at the moment, and anyways, those are some of the primary issues.

How can I replicate these effectively features in SwiftUI? I would like to be able to activate this from a child view (like a child view in a separate file, not the root view).

Note: Interfacing with UIKit is a totally acceptable solution as long as it is only an implementation detail and acts as a regular SwiftUI view does for the most part.

Thank you!

Body:
I was trying to do something similar to this. Here is a half-finished solution (no Geometry Reader to push up the screen, and not using BlurView).

For me, the critical stumbling block was using the mask on the TapGesture, otherwise my onTapGesture's that I previously used swallowed all Form taps.

struct BottomSheetPicker: View {
    @Binding var selection: Double

    var min: Double = 0.0
    let max: Double
    var by: Double = 1.0
    var format: String = "%d"

    var body: some View {
        Group {
            Picker("", selection: $selection) {
                ForEach(Array(stride(from: min, through: max, by: by)), id: \.self) { item in
                    Text(String(format: self.format, item))
                }
            }
            .pickerStyle(WheelPickerStyle())
            .foregroundColor(.white)
            .frame(height: 180)
            .padding()
        }.background(Color.gray)
    }
}

And here is the main content view:

struct MyContentView: View {
    @State private var heightCm = 0.0
    @State private var weightKg = 0.0

    @State private var pickerType = 0 // TODO: Update to Enum
    private var isShowingOverlay: Bool {
        get {
            return self.pickerType != 0
        }
    }

    private let heightFormat = "%.0f cm"
    private let weightFormat = "%.1f kg"

    private var heightPicker: some View {
        BottomSheetPicker(selection: $heightCm, max: 300, format: heightFormat)
    }

    private var weightPicker: some View {
        BottomSheetPicker(selection: $weightKg, max: 200, by: 0.5, format: weightFormat)
    }

    // There are a few nicer ways to do this, just wanted to whip up a quick demo
    private var pickerOverlay: some View {
        Group {
            if pickerType == 1 {
                heightPicker
            } else if pickerType == 2 {
                weightPicker
            } else {
                EmptyView()
            }
        }
    }

    var body: some View {
        ZStack {
            Form {
                Section(header: Text("Personal Information")) {
                    HStack {
                        Text("Height")
                        Spacer()
                        Text(String(format: heightFormat, self.heightCm))
                    }
                    .contentShape(Rectangle())
                    .onTapGesture {
                        self.pickerType = 1
                    }

                    HStack {
                        Text("Weight")
                        Spacer()
                        Text(String(format: weightFormat, self.weightKg))
                    }
                    .contentShape(Rectangle())
                    .onTapGesture {
                        self.pickerType = 2
                    }
                }
            }
            .gesture(TapGesture().onEnded({
                self.pickerType = 0
            }), including: isShowingOverlay ? .all : .none)

            if isShowingOverlay {
                pickerOverlay
                    .frame(alignment: .bottom)
                    .transition(AnyTransition.move(edge: .bottom))
                    .animation(.easeInOut(duration: 0.5))
            }
        }
    }
}


来源: stackexchange

问:
Incrementing the name attribute of cloned inputs in jquery
I have a specific section of a form(a select box and three checkboxes) that needs to be duplicated upon request. I have the clone of the div working as well as the incrementing of that specific div, but I am having issues incrementing the checboxes itself to make it unique.

Here is my HTML:

```<code><div class="orgboxdupe" style="border: 1px solid lightgrey; padding-left:20px;padding-right:20px;padding-bottom:20px;margin-top:10px; width: 600px;">
   <h3>Add user to an organization</h3>
   <select id="orggroupadd" class="user_groupadd" name="user_orggroupadd[]">
      <option value="none">Select an organization</option>
      <option value="152">Test4</option>
      <option value="156">test9</option>
   </select>
   <br><br>Organization Admin (can view uploaded files): <input type="checkbox" name="orgadmincheckbox2"><br><br>c3 Access: <input type="checkbox" name="c3checkbox2"> c4 Access: <input type="checkbox" name="c4checkbox2">
</div>
</code>```

On button click it creates a new orgboxdupe box with an incrementing ID but for some reason it increments the number on the first div checkboxes and not on the subsequent cloned checkboxes:

Here is my JS

```<code>//Portalorgs - add Users
//Vars
let  $addnewgroupbutton = jQuery( "#addnewgroup" );
let  $mainelement = jQuery("#orguserbox");
let  $dupebox = jQuery(".orgboxdupe");
let  $selectboxid = jQuery("#orggroupadd");
let   $checkboxes = jQuery("input[type='checkbox']");
let  $cloneindex = 1;

//Duplicating add organizations box for users - po-addusers.php
$addnewgroupbutton.click(function() {
    $cloneindex++;
    $dupebox.clone().appendTo($mainelement).attr("id","user_orggroupadd" + $cloneindex).find(':checked').attr('checked', false);
    $checkboxes.each(function(){
    jQuery(this).attr("name",jQuery(this).attr("name") + $cloneindex);
  });
  console.log($cloneindex);
});
</code>```

Thanks for any help that can be provided.

答:
As noted by @Taplar $checkboxes references the original checkboxes. So they are the ones being updated each time there's a click.

You need to reference the checkboxes in the just copied clone; you can use chaining like so:

```<code>    ....
    .end().find(':checkbox').attr('name', function() {
        return this.name + $cloneindex;
    });
</code>```

//Portalorgs - add Users
//Vars
let  $addnewgroupbutton = jQuery( "#addnewgroup" );
let  $mainelement = jQuery("#orguserbox");
let  $dupebox = jQuery(".orgboxdupe");
let  $selectboxid = jQuery("#orggroupadd");
let   $checkboxes = jQuery("input[type='checkbox']");
let  $cloneindex = 1;

//Duplicating add organizations box for users - po-addusers.php
$addnewgroupbutton.click(function() {
    $cloneindex++;
    $dupebox.clone().appendTo($mainelement).attr("id","user_orggroupadd" + $cloneindex).find(':checked').attr('checked', false)
    //operate on the close via method chaining
    .end().find(':checkbox').attr('name', function() {
        return this.name + $cloneindex;
    });
    /*$checkboxes.each(function(){
    jQuery(this).attr("name",jQuery(this).attr("name") + $cloneindex);
  });*/
  //console.log($cloneindex);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="addnewgroup">Add New Group</button>
<div id="orguserbox">
<div class="orgboxdupe" style="border: 1px solid lightgrey; padding-left:20px;padding-right:20px;padding-bottom:20px;margin-top:10px; width: 600px;">
   <h3>Add user to an organization</h3>
   <select id="orggroupadd" class="user_groupadd" name="user_orggroupadd[]">
      <option value="none">Select an organization</option>
      <option value="152">Test4</option>
      <option value="156">test9</option>
   </select>
   <br><br>Organization Admin (can view uploaded files): <input type="checkbox" name="orgadmincheckbox2"><br><br>c3 Access: <input type="checkbox" name="c3checkbox2">
   </div>
   </div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a specific section of a form(a select box and three checkboxes) that needs to be duplicated upon request. I have the clone of the div working as well as the incrementing of that specific div, but I am having issues incrementing the checboxes itself to make it unique.

Here is my HTML:

Add user to an organization

   <select id="orggroupadd" class="user_groupadd" name="user_orggroupadd[]">
      <option value="none">Select an organization</option>
      <option value="152">Test4</option>
      <option value="156">test9</option>
   </select>

Organization Admin (can view uploaded files): <input type="checkbox" name="orgadmincheckbox2">

c3 Access: <input type="checkbox" name="c3checkbox2"> c4 Access: <input type="checkbox" name="c4checkbox2">

On button click it creates a new orgboxdupe box with an incrementing ID but for some reason it increments the number on the first div checkboxes and not on the subsequent cloned checkboxes:

Here is my JS

//Portalorgs - add Users
//Vars
let  $addnewgroupbutton = jQuery( "#addnewgroup" );
let  $mainelement = jQuery("#orguserbox");
let  $dupebox = jQuery(".orgboxdupe");
let  $selectboxid = jQuery("#orggroupadd");
let   $checkboxes = jQuery("input[type='checkbox']");
let  $cloneindex = 1;

//Duplicating add organizations box for users - po-addusers.php
$addnewgroupbutton.click(function() {
    $cloneindex++;
    $dupebox.clone().appendTo($mainelement).attr("id","user_orggroupadd" + $cloneindex).find(':checked').attr('checked', false);
    $checkboxes.each(function(){
    jQuery(this).attr("name",jQuery(this).attr("name") + $cloneindex);
  });
  console.log($cloneindex);
});

Thanks for any help that can be provided.

Body:
As noted by @Taplar $checkboxes references the original checkboxes. So they are the ones being updated each time there's a click.

You need to reference the checkboxes in the just copied clone; you can use chaining like so:

    ....
    .end().find(':checkbox').attr('name', function() {
        return this.name + $cloneindex;
    });

//Portalorgs - add Users
//Vars
let  $addnewgroupbutton = jQuery( "#addnewgroup" );
let  $mainelement = jQuery("#orguserbox");
let  $dupebox = jQuery(".orgboxdupe");
let  $selectboxid = jQuery("#orggroupadd");
let   $checkboxes = jQuery("input[type='checkbox']");
let  $cloneindex = 1;

//Duplicating add organizations box for users - po-addusers.php
$addnewgroupbutton.click(function() {
    $cloneindex++;
    $dupebox.clone().appendTo($mainelement).attr("id","user_orggroupadd" + $cloneindex).find(':checked').attr('checked', false)
    //operate on the close via method chaining
    .end().find(':checkbox').attr('name', function() {
        return this.name + $cloneindex;
    });
    /*$checkboxes.each(function(){
    jQuery(this).attr("name",jQuery(this).attr("name") + $cloneindex);
  });*/
  //console.log($cloneindex);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="addnewgroup">Add New Group</button>
<div id="orguserbox">
<div class="orgboxdupe" style="border: 1px solid lightgrey; padding-left:20px;padding-right:20px;padding-bottom:20px;margin-top:10px; width: 600px;">
   <h3>Add user to an organization</h3>
   <select id="orggroupadd" class="user_groupadd" name="user_orggroupadd[]">
      <option value="none">Select an organization</option>
      <option value="152">Test4</option>
      <option value="156">test9</option>
   </select>
   <br><br>Organization Admin (can view uploaded files): <input type="checkbox" name="orgadmincheckbox2"><br><br>c3 Access: <input type="checkbox" name="c3checkbox2">
   </div>
   </div>


问:
Boundary superpixels and adjacency matrix
Looking for a method to determine adjacent superpixels, I found this interesting solution.
However, as I know, there is need to consider adjacency between superpixels which are located in the left and right boundaries. Also the adjacency for superpixels in top and bottom boundaries should be taken into account.

For example, in the above figure the red-filled superpixels should be considered as neighbor ones.

Any idea for that?

答:
The simplest way to extend the given answer to a toroidal boundary condition (periodicity along the vertical axis and along the horizontal axis corresponds to mapping the image onto the surface of a torus) is to add the first row of the image as a new, last row, and similarly for the columns. That is, we explicitly make the labels in the first column to be neighbors to the labels in the last column.

This one-liner accomplishes the required replication:

```<code>L = L([1:end,1],[1:end,1]);
</code>```

Insert this line after creating L through the call to superpixels, and before calling graycomatrix.

Body:
The simplest way to extend the given answer to a toroidal boundary condition (periodicity along the vertical axis and along the horizontal axis corresponds to mapping the image onto the surface of a torus) is to add the first row of the image as a new, last row, and similarly for the columns. That is, we explicitly make the labels in the first column to be neighbors to the labels in the last column.

This one-liner accomplishes the required replication:

L = L([1:end,1],[1:end,1]);

Insert this line after creating L through the call to superpixels, and before calling graycomatrix.


问:
PowerShell Jobs vs Start-Process
I made a little diagnostic script that I keep in my $profile. In collecting the CPU name I found that the command takes about 4 seconds (Get-WmiObject -Class Win32_Processor).Name. So I thought I'd try PowerShell Jobs and while I think they will be really good for long background jobs, if you just want to quickly grab a small piece of information in the background, the initialisation times are awkward (like 2-3 sec per job) so I thought I'd use Start-Process to dump values in temp files while the rest of my script runs. I think I'm doing this correctly, but if you run this function 3 or 4 times, you'll notice that CPU name is not populated.

• Is using Start-Process like this optimal, or does anyone have a quicker way to just start small jobs in the background in parallel? I know there is a .NET way of doing this (but it seems super-complex from what I've seen)?

• Do you know why my "wait for file to be created and be non-zero before accessing it" is failing so regularly?

```<code>function sys {
    $System = get-wmiobject -class "Win32_ComputerSystem"
    $Mem = [math]::Ceiling($System.TotalPhysicalMemory / 1024 / 1024 / 1024)

    $wmi = gwmi -class Win32_OperatingSystem -computer "."
    $LBTime = $wmi.ConvertToDateTime($wmi.Lastbootuptime)
    [TimeSpan]$uptime = New-TimeSpan $LBTime $(get-date)
    $s = "" ; if ($uptime.Days -ne 1) {$s = "s"}
    $uptime_string = "$($uptime.days) day$s $($uptime.hours) hr $($uptime.minutes) min $($uptime.seconds) sec"

    $temp_cpu = "$($env:TEMP)\ps_temp_cpu.txt"
    $temp_cpu_cores = "$($env:TEMP)\ps_temp_cpu_cores.txt"
    $temp_cpu_logical = "$($env:TEMP)\ps_temp_cpu_logical.txt"
    rm -force $temp_cpu -EA silent ; rm -force $temp_cpu_cores -EA silent ; rm -force $temp_cpu_logical -EA silent
    Start-Process -NoNewWindow -FilePath "powershell.exe" -ArgumentList "-NoLogo -NoProfile (Get-WmiObject -Class Win32_Processor).Name > $temp_cpu"
    Start-Process -NoNewWindow -FilePath "powershell.exe" -ArgumentList "-NoLogo -NoProfile (Get-WmiObject -Class Win32_Processor).NumberOfCores > $temp_cpu_cores"
    Start-Process -NoNewWindow -FilePath "powershell.exe" -ArgumentList "-NoLogo -NoProfile (Get-WmiObject -Class Win32_Processor).NumberOfLogicalProcessors > $temp_cpu_logical"
    ""
    "Hostname:          $($System.Name)"
    "Domain:            $($System.Domain)"
    "PrimaryOwner:      $($System.PrimaryOwnerName)"
    "Make/Model:        $($System.Manufacturer) ($($System.Model))"  #     "ComputerModel:  $((Get-WmiObject -Class:Win32_ComputerSystem).Model)"
    "SerialNumber:      $((Get-WmiObject -Class:Win32_BIOS).SerialNumber)"
    "PowerShell:        $($PSVersionTable.PSVersion)"
    "Windows Version:   $($PSVersionTable.BuildVersion)"
    "Windows ReleaseId: $((Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'ReleaseId').ReleaseId)"
    "Display Card:      $((Get-WmiObject -Class:Win32_VideoController).Name)"
    "Display Driver:    $((Get-WmiObject -Class:Win32_VideoController).DriverVersion)"
    "Display ModelDesc: $((Get-WmiObject -Class:Win32_VideoController).VideoModeDescription)"
    "Last Boot Time:    $([Management.ManagementDateTimeConverter]::ToDateTime((Get-WmiObject Win32_OperatingSystem | select 'LastBootUpTime').LastBootUpTime))"   # $(wmic OS get LastBootupTime)
    "Uptime:            $uptime_string"
    # ipconfig | sls IPv4
    Get-Netipaddress | where AddressFamily -eq IPv4 | select IPAddress,InterfaceIndex,InterfaceAlias | sort InterfaceIndex

    # Get-PSDrive | sort -Descending Free | Format-Table
    # https://stackoverflow.com/questions/37154375/display-disk-size-and-freespace-in-gb
    # https://www.petri.com/checking-system-drive-free-space-with-wmi-and-powershell
    # https://www.oxfordsbsguy.com/2017/02/08/powershell-how-to-check-for-drives-with-less-than-10gb-of-free-diskspace/
    # Get-Volume | Where-Object {($_.SizeRemaining -lt 10000000000) -and ($_.DriveType -eq “FIXED”) -and ($_.FileSystemLabel -ne “System Reserved”)}
    gwmi win32_logicaldisk | Format-Table DeviceId, VolumeName, @{n="Size(GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="Free(GB)";e={[math]::Round($_.FreeSpace/1GB,2)}}

    # Note: -EA silent on Get-Item otherwise get an error
    while (!(Test-Path $temp_cpu)) { while ((Get-Item $temp_cpu -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    "CPU:               $(cat $temp_cpu)"
    while (!(Test-Path $temp_cpu_cores)) { while ((Get-Item $temp_cpu_cores -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    "CPU Cores:         $(cat $temp_cpu_cores)"
    while (!(Test-Path $temp_cpu_logical)) { while ((Get-Item $temp_cpu_logical -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    "CPU Logical:       $(cat $temp_cpu_logical)"
    rm -force $temp_cpu -EA silent ; rm -force $temp_cpu_cores -EA silent ; rm -force $temp_cpu_logical -EA silent
    "Memory:            $(Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | Foreach {"{0:N2}" -f ([math]::round(($_.Sum / 1GB),2))}) GB"
    ""
    "Also note the 'Get-ComputerInfo' Cmdlet (has more info but slower to run)"
    ""
}
</code>```

答:
To run jobs in background in powershell, there are these 3 ways to go about it

```
<code>
1. Invoke-Command<sup>[3]</sup> -scriptblock { script }  -asJob -computername localhost
2. Start-Job<sup>[2]</sup> -scriptblock { script }
3. Start-Process<sup>[1]</sup> powershell {script}
</code>
```

If you truly want to run things in the background with each job being independent of each other, you'll have to think about using the first or second option as neither of them require the output to be written to a file.

Invoke-Command starts a new session with the system and runs the job in a new instance.

Start-Job creates a new job in the background under a new powershell instance, takes a little more time to allocate the resources and start the process. Just like start-process, Start-Job will run the job in a separate powershell.exe instance.

Start-Process requires you to redirect the standard output to a file[1]. You have to rely on the performance of the disk and how fast your reads and writes are. You also have to ensure that no more than one thread is reading/writing to the output of this process.

Recommendation
I found Invoke-Command to be the fastest when running 100 concurrent jobs to get the processor info. This option does require you to provide -ComputerName which then requires you to be an admin to start a winrm Session with localhost. If you dont output the job information while creating the jobs, it does not take away any significant time.

Start-Job and Invoke-Command both took about a second to get the processor info and running 100 concurrent jobs to get the same thing took some overhead.

```<code>$x = 0..100 | Invoke-Command -computername localhost -scriptblock { script } -asJob
$x | % { $_ | wait-job | out-null }
$output = $x | % { $_ | Receive-Job}
# You can run measure-object, sort-object, etc as well
</code>```

[1]Start-Process

RedirectStandardOutput: Specifies a file. This cmdlet sends the output generated by the process to a file that you specify. Enter the path and filename. By default, the output is displayed in the console.

[2]Start-Job

The Start-Job cmdlet starts a PowerShell background job on the local computer. ... A PowerShell background job runs a command without interacting with the current session.

[3]Invoke-Command

The Invoke-Command cmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. ... To run a command in a background job, use the AsJob parameter

Title: PowerShell Jobs vs Start-Process

Body:
I made a little diagnostic script that I keep in my $profile. In collecting the CPU name I found that the command takes about 4 seconds (Get-WmiObject -Class Win32_Processor).Name. So I thought I'd try PowerShell Jobs and while I think they will be really good for long background jobs, if you just want to quickly grab a small piece of information in the background, the initialisation times are awkward (like 2-3 sec per job) so I thought I'd use Start-Process to dump values in temp files while the rest of my script runs. I think I'm doing this correctly, but if you run this function 3 or 4 times, you'll notice that CPU name is not populated.

• Is using Start-Process like this optimal, or does anyone have a quicker way to just start small jobs in the background in parallel? I know there is a .NET way of doing this (but it seems super-complex from what I've seen)?

• Do you know why my "wait for file to be created and be non-zero before accessing it" is failing so regularly?

function sys {
    $System = get-wmiobject -class "Win32_ComputerSystem"
    $Mem = [math]::Ceiling($System.TotalPhysicalMemory / 1024 / 1024 / 1024)

    $wmi = gwmi -class Win32_OperatingSystem -computer "."
    $LBTime = $wmi.ConvertToDateTime($wmi.Lastbootuptime)
    [TimeSpan]$uptime = New-TimeSpan $LBTime $(get-date)
    $s = "" ; if ($uptime.Days -ne 1) {$s = "s"}
    $uptime_string = "$($uptime.days) day$s $($uptime.hours) hr $($uptime.minutes) min $($uptime.seconds) sec"

    $temp_cpu = "$($env:TEMP)\ps_temp_cpu.txt"
    $temp_cpu_cores = "$($env:TEMP)\ps_temp_cpu_cores.txt"
    $temp_cpu_logical = "$($env:TEMP)\ps_temp_cpu_logical.txt"
    rm -force $temp_cpu -EA silent ; rm -force $temp_cpu_cores -EA silent ; rm -force $temp_cpu_logical -EA silent
    Start-Process -NoNewWindow -FilePath "powershell.exe" -ArgumentList "-NoLogo -NoProfile (Get-WmiObject -Class Win32_Processor).Name > $temp_cpu"
    Start-Process -NoNewWindow -FilePath "powershell.exe" -ArgumentList "-NoLogo -NoProfile (Get-WmiObject -Class Win32_Processor).NumberOfCores > $temp_cpu_cores"
    Start-Process -NoNewWindow -FilePath "powershell.exe" -ArgumentList "-NoLogo -NoProfile (Get-WmiObject -Class Win32_Processor).NumberOfLogicalProcessors > $temp_cpu_logical"
    ""
    "Hostname:          $($System.Name)"
    "Domain:            $($System.Domain)"
    "PrimaryOwner:      $($System.PrimaryOwnerName)"
    "Make/Model:        $($System.Manufacturer) ($($System.Model))"  #     "ComputerModel:  $((Get-WmiObject -Class:Win32_ComputerSystem).Model)"
    "SerialNumber:      $((Get-WmiObject -Class:Win32_BIOS).SerialNumber)"
    "PowerShell:        $($PSVersionTable.PSVersion)"
    "Windows Version:   $($PSVersionTable.BuildVersion)"
    "Windows ReleaseId: $((Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'ReleaseId').ReleaseId)"
    "Display Card:      $((Get-WmiObject -Class:Win32_VideoController).Name)"
    "Display Driver:    $((Get-WmiObject -Class:Win32_VideoController).DriverVersion)"
    "Display ModelDesc: $((Get-WmiObject -Class:Win32_VideoController).VideoModeDescription)"
    "Last Boot Time:    $([Management.ManagementDateTimeConverter]::ToDateTime((Get-WmiObject Win32_OperatingSystem | select 'LastBootUpTime').LastBootUpTime))"   # $(wmic OS get LastBootupTime)
    "Uptime:            $uptime_string"
    # ipconfig | sls IPv4
    Get-Netipaddress | where AddressFamily -eq IPv4 | select IPAddress,InterfaceIndex,InterfaceAlias | sort InterfaceIndex

    # Get-PSDrive | sort -Descending Free | Format-Table
    # https://stackoverflow.com/questions/37154375/display-disk-size-and-freespace-in-gb
    # https://www.petri.com/checking-system-drive-free-space-with-wmi-and-powershell
    # https://www.oxfordsbsguy.com/2017/02/08/powershell-how-to-check-for-drives-with-less-than-10gb-of-free-diskspace/
    # Get-Volume | Where-Object {($_.SizeRemaining -lt 10000000000) -and ($_.DriveType -eq “FIXED”) -and ($_.FileSystemLabel -ne “System Reserved”)}
    gwmi win32_logicaldisk | Format-Table DeviceId, VolumeName, @{n="Size(GB)";e={[math]::Round($_.Size/1GB,2)}},@{n="Free(GB)";e={[math]::Round($_.FreeSpace/1GB,2)}}

    # Note: -EA silent on Get-Item otherwise get an error
    while (!(Test-Path $temp_cpu)) { while ((Get-Item $temp_cpu -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    "CPU:               $(cat $temp_cpu)"
    while (!(Test-Path $temp_cpu_cores)) { while ((Get-Item $temp_cpu_cores -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    "CPU Cores:         $(cat $temp_cpu_cores)"
    while (!(Test-Path $temp_cpu_logical)) { while ((Get-Item $temp_cpu_logical -EA silent).length -eq 0kb) { Start-Sleep -Milliseconds 500 } }
    "CPU Logical:       $(cat $temp_cpu_logical)"
    rm -force $temp_cpu -EA silent ; rm -force $temp_cpu_cores -EA silent ; rm -force $temp_cpu_logical -EA silent
    "Memory:            $(Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | Foreach {"{0:N2}" -f ([math]::round(($_.Sum / 1GB),2))}) GB"
    ""
    "Also note the 'Get-ComputerInfo' Cmdlet (has more info but slower to run)"
    ""
}

Body:
To run jobs in background in powershell, there are these 3 ways to go about it

1. Invoke-Command[3] -scriptblock { script }  -asJob -computername localhost
2. Start-Job[2] -scriptblock { script }
3. Start-Process[1] powershell {script}

If you truly want to run things in the background with each job being independent of each other, you'll have to think about using the first or second option as neither of them require the output to be written to a file.

Invoke-Command starts a new session with the system and runs the job in a new instance.

Start-Job creates a new job in the background under a new powershell instance, takes a little more time to allocate the resources and start the process. Just like start-process, Start-Job will run the job in a separate powershell.exe instance.

Start-Process requires you to redirect the standard output to a file[1]. You have to rely on the performance of the disk and how fast your reads and writes are. You also have to ensure that no more than one thread is reading/writing to the output of this process.

Recommendation
I found Invoke-Command to be the fastest when running 100 concurrent jobs to get the processor info. This option does require you to provide -ComputerName which then requires you to be an admin to start a winrm Session with localhost. If you dont output the job information while creating the jobs, it does not take away any significant time.

Start-Job and Invoke-Command both took about a second to get the processor info and running 100 concurrent jobs to get the same thing took some overhead.

$x = 0..100 | Invoke-Command -computername localhost -scriptblock { script } -asJob
$x | % { $_ | wait-job | out-null }
$output = $x | % { $_ | Receive-Job}
# You can run measure-object, sort-object, etc as well

[1]Start-Process

RedirectStandardOutput: Specifies a file. This cmdlet sends the output generated by the process to a file that you specify. Enter the path and filename. By default, the output is displayed in the console.

[2]Start-Job

The Start-Job cmdlet starts a PowerShell background job on the local computer. ... A PowerShell background job runs a command without interacting with the current session.

[3]Invoke-Command

The Invoke-Command cmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. ... To run a command in a background job, use the AsJob parameter


问:
Where to find stored results from a Cloud Speech-to-Text API call?
I am performing a batch of asynchronous long_running_recognize transcriptions using Google's Cloud Speech-to-Text, and it appears that some of my requests are timing out, and/or not returning anything. How may I access the stored results of my API calls? I'm using Python 3.7.

I realize that the API call returns results to the function that made the call. What I'm asking is, does Google store the results of my API calls somewhere? And how do I access them?

答:
You should probably call the asynchronous method when submitting larger audio files. Specifically this calls the LongRunningRecognize method. This should submit a Long Running Operation and should return an immediate response, for example:

```<code>{
  "name": "operation_name",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeMetadata"
    "progressPercent": 34,
    "startTime": "2016-08-30T23:26:29.579144Z",
    "lastUpdateTime": "2016-08-30T23:26:29.826903Z"
  }
}
</code>```

With this response you can poll for the result given the operation_name:

```<code>curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     "https://speech.googleapis.com/v1/operations/your-operation-name"
</code>```

Note: when you are not receiving any return values using this method, I would suggest increasing the timeout and retry of the client. This can be done with something like:

```<code>long_running_recognize(retry=10, timeout=300)
</code>```

Source

Body:
You should probably call the asynchronous method when submitting larger audio files. Specifically this calls the LongRunningRecognize method. This should submit a Long Running Operation and should return an immediate response, for example:

{
  "name": "operation_name",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeMetadata"
    "progressPercent": 34,
    "startTime": "2016-08-30T23:26:29.579144Z",
    "lastUpdateTime": "2016-08-30T23:26:29.826903Z"
  }
}

With this response you can poll for the result given the operation_name:

curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     "https://speech.googleapis.com/v1/operations/your-operation-name"

Note: when you are not receiving any return values using this method, I would suggest increasing the timeout and retry of the client. This can be done with something like:

long_running_recognize(retry=10, timeout=300)

Source


问:
Working with large numbers in PHP
To use modular exponentiation as you would require when using the Fermat Primality Test with large numbers (100,000+), it calls for some very large calculations.

When I multiply two large numbers (eg: 62574 and 62574) PHP seems to cast the result to a float. Getting the modulus value of that returns strange values.

```<code>$x = 62574 * 62574;
var_dump($x);          // float(3915505476) ... correct
var_dump($x % 104659); // int(-72945)  ... wtf.
</code>```

Is there any way to make PHP perform these calculations properly? Alternatively, is there another method for finding modulus values that would work for large numbers?

OwnerDisplayName: nickf

ContentLicense: CC BY-SA 2.5

Title: Working with large numbers in PHP

Body:
To use modular exponentiation as you would require when using the Fermat Primality Test with large numbers (100,000+), it calls for some very large calculations.

When I multiply two large numbers (eg: 62574 and 62574) PHP seems to cast the result to a float. Getting the modulus value of that returns strange values.

$x = 62574 * 62574;
var_dump($x);          // float(3915505476) ... correct
var_dump($x % 104659); // int(-72945)  ... wtf.

Is there any way to make PHP perform these calculations properly? Alternatively, is there another method for finding modulus values that would work for large numbers?

LastEditorDisplayName: sanxiyn

Body:
use this

 $num1 = "123456789012345678901234567890";
 $num2 = "9876543210";
 $r    = mysql_query("Select @sum:=$num1 + $num2");
 $sumR = mysql_fetch_row($r);
 $sum  = $sumR[0];

ContentLicense: CC BY-SA 3.0


问:
What can I use to stop a loop instead of 'return 0'?
so I made a simple loop that finds out if an array has the elements with the values of 0 and 1.
if the loop indeed finds 0 or 1 inside of the array, it will say "YES", otherwise "NO".
yes, the program works just fine, but at the end of the program it prints out "YES" or "NO" as many times as i put cin>>dim to.
for example if dim which means (dimension[of the array]) is 5 it's going to print either "YESYESYESYESYES" or "NONONONONO"
I have to use return 0 in order to make it print it out like once, but I feel like this is not the right way to do it. Please help me with this. thanks!

```<code>#include <bits/stdc++.h>
using namespace std;
int main()
{
int i, dim, v[100];
cin>>dim;
for(i=0;i<dim;i++)
    cin>>v[i];
for(i=0;i<dim;i++)
    if(v[i]==0 || v[i]==1){
        cout<<"YES"; return 0;}
    else{
        cout<<"NO"; return 0;}
  return 0;
}
</code>```

答:
Even better, you can actually check if v[i]==0 or 1 inside the input for loop immediately after taking input and set a flag to true. Depending on requirement, you can either break or wait until the entire input is read and then come out and check for flag==true and then print "YES" and print "NO" if flag==false.
This will save you running the loop again to check for 0 or 1.</p>

Body:
so I made a simple loop that finds out if an array has the elements with the values of 0 and 1.
if the loop indeed finds 0 or 1 inside of the array, it will say "YES", otherwise "NO".
yes, the program works just fine, but at the end of the program it prints out "YES" or "NO" as many times as i put cin>>dim to.
for example if dim which means (dimension[of the array]) is 5 it's going to print either "YESYESYESYESYES" or "NONONONONO"
I have to use return 0 in order to make it print it out like once, but I feel like this is not the right way to do it. Please help me with this. thanks!

#include <bits/stdc++.h>
using namespace std;
int main()
{
int i, dim, v[100];
cin>>dim;
for(i=0;i<dim;i++)
    cin>>v[i];
for(i=0;i<dim;i++)
    if(v[i]==0 || v[i]==1){
        cout<<"YES"; return 0;}
    else{
        cout<<"NO"; return 0;}
  return 0;
}


问:
Why I should break distinct count measures into separate measure groups?
When I am trying to create DistinctCount measure in VS 2008 OLAP project, it creates it in separate group instead original group that I want.
Therefore, I created it in two steps.
I created measure without aggregation in needed group and then set AggregationFunction to DistinctCount manually.

Then I've built project and deployed. Everything works fine except warning in OLAP project. My measure is highlighted by a blue wavy line and it says:

Break distinct count measures into separate measure groups

Why should I do it and is it safe to ignore this warning?

答:
Referring to the Microsoft white paper entitled "Analysis Services Distinct Count Optimization":

As a quick high-level overview of distinct count calculations, the distinct count measure is not designed like other measures (such as sum, count, max, min, and so on). Distinct counts are difficult to aggregate in comparison to other measures because the former are not fully additive. Because of this, the vast majority of distinct count queries are calculated at run time at the leaf level granularity, specifically the unique values of the distinct count measure. This means that the Analysis Services storage engine parses the source column and treats it almost like an attribute that has been GROUPED BY with an implicit count for each row.

Later they mentioned that:

As previously noted, this is because the distinct count measure is architecturally different than other measures. You cannot have more than one distinct measure because you cannot order a MEASURE GROUP by many measures. The distinct count measure is also at a lower level of granularity than SUM and COUNT measures. By adding other measures to the measure group holding a distinct count measure, all of the other measures will be at the same granularity as the distinct count measure, resulting in inefficient data structures and suboptimal queries. To perform distinct count aggregations, each distinct count measure still retains its unique combination of dimension key attributes.

You can download the white paper from the following link:

Analysis Services Distinct Count Optimization


问:
Image not loaded on template
Image not loaded on template,
This is my view

```<code>ob = article.objects.raw("select * from blogapp_article as a inner join blogapp_useradd as b on a.userid=b.uname ORDER BY a.id DESC")
</code>```

'data1': ob

On template

```<code>{% for item in data1 %}
        <img src="{{ item.upic.url }}" style="width: 60px">
        {% endfor %}
</code>```

models.py

```<code>class useradd(models.Model):
    uname = models.EmailField(max_length=20)
    pswd = models.CharField(max_length=20)
    upic=models.ImageField(upload_to='')
    country = models.CharField(max_length=50,default='India')
    contact = models.IntegerField(default='0123456789')

class article(models.Model):
    content = models.CharField(max_length=20,default='content')
    title = models.CharField(max_length=20,default='title')
    d_and_t = models.CharField(max_length=20)
    userid = models.CharField(max_length=20,default='local_01')
</code>```

答:
You must configuring static files management.It is very clear.
Firstly you must define your static file path and static url in your settings.py file

```<code>STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/', # your static files path here
]
</code>```

After that, you must add static url definition to your urls.py

```<code>from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Finally, you must use {% static 'file_name'%} template tag in your templates like that:

```<code>{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">
</code>```

Please look up for detail managing static files

Title: Image not loaded on template

Body:
Image not loaded on template,
This is my view

ob = article.objects.raw("select * from blogapp_article as a inner join blogapp_useradd as b on a.userid=b.uname ORDER BY a.id DESC")

'data1': ob

On template

{% for item in data1 %}

        {% endfor %}

models.py

class useradd(models.Model):
    uname = models.EmailField(max_length=20)
    pswd = models.CharField(max_length=20)
    upic=models.ImageField(upload_to='')
    country = models.CharField(max_length=50,default='India')
    contact = models.IntegerField(default='0123456789')

class article(models.Model):
    content = models.CharField(max_length=20,default='content')
    title = models.CharField(max_length=20,default='title')
    d_and_t = models.CharField(max_length=20)
    userid = models.CharField(max_length=20,default='local_01')

Body:
You must configuring static files management.It is very clear.
Firstly you must define your static file path and static url in your settings.py file

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/', # your static files path here
]

After that, you must add static url definition to your urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Finally, you must use {% static 'file_name'%} template tag in your templates like that:

{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">

Please look up for detail managing static files


问:
Android: How to get values in under specific xml tags
I want to get values under specific tags of my xml file (accessed via url) which look like this:

```<code><SyncLoginResponse>
    <Videos>
    <Video>
        <name>27/flv</name>
        <title>scooter</title>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
        <thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/106/jpg</thumbnail>

    </Video>
    <Video>
        <name>26/flv</name>
        <title>barsNtone</title>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
        <thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/104/jpg</thumbnail>
    </Video>

    </Videos>
    <Slideshows>
    <Slideshow>
        <name>44</name>
        <title>ProcessFlow</title>
        <pages>4</pages>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/</url>

    </Slideshow>
    </Slideshows>
<SyncLoginResponse>
</code>```

As you can see, there are "name" tags under video while there is also "name" tag under slideshow as well as "title" and "url". I want to get the values under slideshow tag.

So far, I have the following codes:

EngagiaSync.java:

```<code>package com.example.engagiasync;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class EngagiaSync extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;
    public String FileName = "";
    public String FileURL = "";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         /* Create a new TextView to display the parsingresult later. */
         TextView tv = new TextView(this);
         tv.setText("...PARSE AND DOWNLOAD...");

         try {
              /* Create a URL we want to load some xml-data from. */
              URL url = new URL("http://somedomain.com/tabletcms/tablets/sync_login/jayem30/jayem");
              url.openConnection();
              /* Get a SAXParser from the SAXPArserFactory. */
              SAXParserFactory spf = SAXParserFactory.newInstance();
              SAXParser sp = spf.newSAXParser();

              /* Get the XMLReader of the SAXParser we created. */
              XMLReader xr = sp.getXMLReader();
              /* Create a new ContentHandler and apply it to the XML-Reader*/
              ExampleHandler myExampleHandler = new ExampleHandler();
              xr.setContentHandler(myExampleHandler);

              /* Parse the xml-data from our URL. */
              xr.parse(new InputSource(url.openStream()));
              /* Parsing has finished. */

              /* Our ExampleHandler now provides the parsed data to us. */
              List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();

              /* Set the result to be displayed in our GUI. */
              //tv.setText(parsedExampleDataSet.toString());
              String currentFile;
              String currentFileURL;
              int x = 1;
              Iterator i;
              i = parsedExampleDataSet.iterator();
              ParsedExampleDataSet dataItem;
              while(i.hasNext()){

                   dataItem = (ParsedExampleDataSet) i.next();

                   tv.append("\nName:> " + dataItem.getName());
                   tv.append("\nTitle:> " + dataItem.getTitle());
                   tv.append("\nPages:> " + dataItem.getPages());
                   tv.append("\nFile:> " + dataItem.getUrl());

                   /*
                   int NumPages = Integer.parseInt(dataItem.getPages());

                   while( x <= NumPages ){
                       currentFile = dataItem.getName() + "-" + x + ".jpg";
                       currentFileURL = dataItem.getUrl() + currentFile;

                       tv.append("\nName: " + dataItem.getName());
                       tv.append("\nTitle: " + dataItem.getTitle());
                       tv.append("\nPages: " + NumPages );
                       tv.append("\nFile: " + currentFile);

                       startDownload(currentFile, currentFileURL);
                       x++;
                   }
                   */

              }

         } catch (Exception e) {
              /* Display any Error to the GUI. */
              tv.setText("Error: " + e.getMessage());

         }
         /* Display the TextView. */
         this.setContentView(tv);
    }

    private void startDownload(String currentFile, String currentFileURL ){
        new DownloadFileAsync().execute(currentFile, currentFileURL);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading files...");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }

    class DownloadFileAsync extends AsyncTask<String, String, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        @Override
        protected String doInBackground(String... strings) {

            try {
                String currentFile = strings[0];
                String currentFileURL = strings[1];

                File root = Environment.getExternalStorageDirectory();
                URL u = new URL(currentFileURL);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();

                int lenghtOfFile = c.getContentLength();

                FileOutputStream f = new FileOutputStream(new File(root + "/download/", currentFile));

                InputStream in = c.getInputStream();

                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;

                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; //total = total + len1
                    publishProgress("" + (int)((total*100)/lenghtOfFile));
                    f.write(buffer, 0, len1);
                }
                f.close();
            } catch (Exception e) {
                Log.d("Downloader", e.getMessage());
            }

            return null;

        }

        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC",progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
       }

       @Override
       protected void onPostExecute(String unused) {
           dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
       }

    }

}
</code>```

ExampleHandler.java:

```<code>package com.example.engagiasync;

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

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ExampleHandler extends DefaultHandler{

     // ===========================================================
     // Fields
     // ===========================================================

     private StringBuilder mStringBuilder = new StringBuilder();

     private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet();
     private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>();

     // ===========================================================
     // Getter & Setter
     // ===========================================================

     public List<ParsedExampleDataSet> getParsedData() {
          return this.mParsedDataSetList;
     }

     // ===========================================================
     // Methods
     // ===========================================================

     /** Gets be called on opening tags like:
      * <tag>
      * Can provide attribute(s), when xml was like:
      * <tag attribute="attributeValue">*/
     @Override
     public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        if (localName.equals("Slideshow")) {
            this.mParsedExampleDataSet = new ParsedExampleDataSet();
        }

     }

     /** Gets be called on closing tags like:
      * </tag> */
     @Override
     public void endElement(String namespaceURI, String localName, String qName)
               throws SAXException {
          if (localName.equals("Slideshow")) {
               this.mParsedDataSetList.add(mParsedExampleDataSet);
          }else if (localName.equals("name")) {
               mParsedExampleDataSet.setName(mStringBuilder.toString().trim());
          }else if (localName.equals("title"))  {
              mParsedExampleDataSet.setTitle(mStringBuilder.toString().trim());
          }else if(localName.equals("pages"))  {
              mParsedExampleDataSet.setPages(mStringBuilder.toString().trim());
          }else if(localName.equals("url")){
              mParsedExampleDataSet.setUrl(mStringBuilder.toString().trim());
          }
          mStringBuilder.setLength(0);
     }

     /** Gets be called on the following structure:
      * <tag>characters</tag> */
     @Override
    public void characters(char ch[], int start, int length) {
          mStringBuilder.append(ch, start, length);
    }
}
</code>```

ParsedExampleDataSet.java:

```<code>package com.example.engagiasync;

public class ParsedExampleDataSet {
    private String name = null;
    private String title = null;
    private String pages = null;
    private String url = null;

    //name
    public String getName() {
         return name;
    }
    public void setName(String name) {
         this.name = name;
    }

    //title
    public String getTitle(){
        return title;
    }
    public void setTitle(String title){
        this.title = title;
    }

    //pages
    public String getPages(){
        return pages;
    }
    public void setPages(String pages){
        this.pages = pages;
    }

    //url
    public String getUrl(){
        return url;
    }
    public void setUrl(String url){
        this.url = url;
    }

    /*
    public String toString(){
         return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address + "\nFile URL: " + this.FileURL + "\n\n";
    }
    */

}
</code>```

The codes above returns the following result in the UI:

```<code>...PARSE AND DOWNLOAD...
Name:> 27/flv
Title:> scooter
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/
</code>```

In which I expect it to be:

```<code>...PARSE AND DOWNLOAD...
Name:> 44
Title:> ProcessFlow
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/
</code>```

答:
try using DOM parser instead of SAX parser....</p>

```<code>input=httpconnection.openHttpConnection(url);
            isr = new InputStreamReader(input);
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.parse(input, null);
            document.getDocumentElement().normalize();
            NodeList videosList = document.getElementsByTagName("Video");
            for (int i = 0; i < videosList .getLength(); i++)
            {
                         Node node = videosList .item(i);
                Element playlistElement = (Element) node;
                NodeList title = playlistElement.getElementsByTagName("name");
                if (title.item(0).getChildNodes().item(0) != null)
                {
                    Element nameElement = (Element) title.item(0);
                    title = nameElement.getChildNodes();
                    Log.v("name===>",((Node) title.item(0)).getNodeValue());
                }

//Like wise use the same code for title ,url ,thumbnail...
            }
</code>```

Body:
I want to get values under specific tags of my xml file (accessed via url) which look like this:

<SyncLoginResponse>
    <Videos>
    <Video>
        <name>27/flv</name>
        <title>scooter</title>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
        <thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/106/jpg</thumbnail>

    </Video>
    <Video>
        <name>26/flv</name>
        <title>barsNtone</title>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
        <thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/104/jpg</thumbnail>
    </Video>

    </Videos>
    <Slideshows>
    <Slideshow>
        <name>44</name>
        <title>ProcessFlow</title>
        <pages>4</pages>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/</url>

    </Slideshow>
    </Slideshows>
<SyncLoginResponse>

As you can see, there are "name" tags under video while there is also "name" tag under slideshow as well as "title" and "url". I want to get the values under slideshow tag.

So far, I have the following codes:

EngagiaSync.java:

package com.example.engagiasync;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class EngagiaSync extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;
    public String FileName = "";
    public String FileURL = "";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         /* Create a new TextView to display the parsingresult later. */
         TextView tv = new TextView(this);
         tv.setText("...PARSE AND DOWNLOAD...");

         try {
              /* Create a URL we want to load some xml-data from. */
              URL url = new URL("http://somedomain.com/tabletcms/tablets/sync_login/jayem30/jayem");
              url.openConnection();
              /* Get a SAXParser from the SAXPArserFactory. */
              SAXParserFactory spf = SAXParserFactory.newInstance();
              SAXParser sp = spf.newSAXParser();

              /* Get the XMLReader of the SAXParser we created. */
              XMLReader xr = sp.getXMLReader();
              /* Create a new ContentHandler and apply it to the XML-Reader*/
              ExampleHandler myExampleHandler = new ExampleHandler();
              xr.setContentHandler(myExampleHandler);

              /* Parse the xml-data from our URL. */
              xr.parse(new InputSource(url.openStream()));
              /* Parsing has finished. */

              /* Our ExampleHandler now provides the parsed data to us. */
              List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();

              /* Set the result to be displayed in our GUI. */
              //tv.setText(parsedExampleDataSet.toString());
              String currentFile;
              String currentFileURL;
              int x = 1;
              Iterator i;
              i = parsedExampleDataSet.iterator();
              ParsedExampleDataSet dataItem;
              while(i.hasNext()){

                   dataItem = (ParsedExampleDataSet) i.next();

                   tv.append("\nName:> " + dataItem.getName());
                   tv.append("\nTitle:> " + dataItem.getTitle());
                   tv.append("\nPages:> " + dataItem.getPages());
                   tv.append("\nFile:> " + dataItem.getUrl());

                   /*
                   int NumPages = Integer.parseInt(dataItem.getPages());

                   while( x <= NumPages ){
                       currentFile = dataItem.getName() + "-" + x + ".jpg";
                       currentFileURL = dataItem.getUrl() + currentFile;

                       tv.append("\nName: " + dataItem.getName());
                       tv.append("\nTitle: " + dataItem.getTitle());
                       tv.append("\nPages: " + NumPages );
                       tv.append("\nFile: " + currentFile);

                       startDownload(currentFile, currentFileURL);
                       x++;
                   }
                   */

              }

         } catch (Exception e) {
              /* Display any Error to the GUI. */
              tv.setText("Error: " + e.getMessage());

         }
         /* Display the TextView. */
         this.setContentView(tv);
    }

    private void startDownload(String currentFile, String currentFileURL ){
        new DownloadFileAsync().execute(currentFile, currentFileURL);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading files...");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }

    class DownloadFileAsync extends AsyncTask<String, String, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        @Override
        protected String doInBackground(String... strings) {

            try {
                String currentFile = strings[0];
                String currentFileURL = strings[1];

                File root = Environment.getExternalStorageDirectory();
                URL u = new URL(currentFileURL);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();

                int lenghtOfFile = c.getContentLength();

                FileOutputStream f = new FileOutputStream(new File(root + "/download/", currentFile));

                InputStream in = c.getInputStream();

                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;

                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; //total = total + len1
                    publishProgress("" + (int)((total*100)/lenghtOfFile));
                    f.write(buffer, 0, len1);
                }
                f.close();
            } catch (Exception e) {
                Log.d("Downloader", e.getMessage());
            }

            return null;

        }

        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC",progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
       }

       @Override
       protected void onPostExecute(String unused) {
           dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
       }

    }

}

ExampleHandler.java:

package com.example.engagiasync;

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

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ExampleHandler extends DefaultHandler{

     // ===========================================================
     // Fields
     // ===========================================================

     private StringBuilder mStringBuilder = new StringBuilder();

     private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet();
     private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>();

     // ===========================================================
     // Getter & Setter
     // ===========================================================

     public List<ParsedExampleDataSet> getParsedData() {
          return this.mParsedDataSetList;
     }

     // ===========================================================
     // Methods
     // ===========================================================

     /** Gets be called on opening tags like:
      * <tag>
      * Can provide attribute(s), when xml was like:
      * <tag attribute="attributeValue">*/
     @Override
     public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        if (localName.equals("Slideshow")) {
            this.mParsedExampleDataSet = new ParsedExampleDataSet();
        }

     }

     /** Gets be called on closing tags like:
      * </tag> */
     @Override
     public void endElement(String namespaceURI, String localName, String qName)
               throws SAXException {
          if (localName.equals("Slideshow")) {
               this.mParsedDataSetList.add(mParsedExampleDataSet);
          }else if (localName.equals("name")) {
               mParsedExampleDataSet.setName(mStringBuilder.toString().trim());
          }else if (localName.equals("title"))  {
              mParsedExampleDataSet.setTitle(mStringBuilder.toString().trim());
          }else if(localName.equals("pages"))  {
              mParsedExampleDataSet.setPages(mStringBuilder.toString().trim());
          }else if(localName.equals("url")){
              mParsedExampleDataSet.setUrl(mStringBuilder.toString().trim());
          }
          mStringBuilder.setLength(0);
     }

     /** Gets be called on the following structure:
      * <tag>characters</tag> */
     @Override
    public void characters(char ch[], int start, int length) {
          mStringBuilder.append(ch, start, length);
    }
}

ParsedExampleDataSet.java:

package com.example.engagiasync;

public class ParsedExampleDataSet {
    private String name = null;
    private String title = null;
    private String pages = null;
    private String url = null;

    //name
    public String getName() {
         return name;
    }
    public void setName(String name) {
         this.name = name;
    }

    //title
    public String getTitle(){
        return title;
    }
    public void setTitle(String title){
        this.title = title;
    }

    //pages
    public String getPages(){
        return pages;
    }
    public void setPages(String pages){
        this.pages = pages;
    }

    //url
    public String getUrl(){
        return url;
    }
    public void setUrl(String url){
        this.url = url;
    }

    /*
    public String toString(){
         return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address + "\nFile URL: " + this.FileURL + "\n\n";
    }
    */

}

The codes above returns the following result in the UI:

...PARSE AND DOWNLOAD...
Name:> 27/flv
Title:> scooter
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/

In which I expect it to be:

...PARSE AND DOWNLOAD...
Name:> 44
Title:> ProcessFlow
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/

Body:
try using DOM parser instead of SAX parser....

input=httpconnection.openHttpConnection(url);
            isr = new InputStreamReader(input);
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.parse(input, null);
            document.getDocumentElement().normalize();
            NodeList videosList = document.getElementsByTagName("Video");
            for (int i = 0; i < videosList .getLength(); i++)
            {
                         Node node = videosList .item(i);
                Element playlistElement = (Element) node;
                NodeList title = playlistElement.getElementsByTagName("name");
                if (title.item(0).getChildNodes().item(0) != null)
                {
                    Element nameElement = (Element) title.item(0);
                    title = nameElement.getChildNodes();
                    Log.v("name===>",((Node) title.item(0)).getNodeValue());
                }

//Like wise use the same code for title ,url ,thumbnail...
            }


问:
React Navigation V5 Hide Bottom Tabs
I would like to be able to hide the tabs on a screen using React Native Navigation v5.

I've been reading the documentation but it doesn't seem like they've updated this for v5 and it refers to the < v4 way of doing things.

here is my code:

```<code>import Home from './components/Home';
import SettingsScreen from './components/Settings';
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';

const SettingsStack = createStackNavigator();
const ProfileStack  = createStackNavigator();

function SettingsStackScreen() {
    return (
        <SettingsStack.Navigator>
            <SettingsStack.Screen name="Settings" component={SettingsScreen} />
        </SettingsStack.Navigator>
    )
}

function ProfileStackScreen() {
    return (
        <ProfileStack.Navigator>
            <ProfileStack.Screen name="Home" component={Home} />
        </ProfileStack.Navigator>
    )
}

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Home" component={ProfileStackScreen} />
        <Tab.Screen name="Settings" component={SettingsStackScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}
</code>```

Things I have tried:

Accessing the options of the function and hiding that way.

Passing tabBarVisible as a prop to the Screen.

What I am asking for is, what is the correct way of hiding tabs on screens in React Navigation v5.

答:
Let's suppose that you want to hide tabs when you are entering Settings. Just add navigation in your constructor:

function SettingsStackScreen({ navigation }) {
    navigation.setOptions({ tabBarVisible: false })
    return (
        <SettingsStack.Navigator>
            <SettingsStack.Screen name="Settings" component={SettingsScreen} />
        </SettingsStack.Navigator>
    )
}
```

This code should work.

Title: React Navigation V5 Hide Bottom Tabs

Body:
I would like to be able to hide the tabs on a screen using React Native Navigation v5.

I've been reading the documentation but it doesn't seem like they've updated this for v5 and it refers to the < v4 way of doing things.

here is my code:

import Home from './components/Home';
import SettingsScreen from './components/Settings';
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';

const SettingsStack = createStackNavigator();
const ProfileStack  = createStackNavigator();

function SettingsStackScreen() {
    return (
        <SettingsStack.Navigator>
            <SettingsStack.Screen name="Settings" component={SettingsScreen} />
        </SettingsStack.Navigator>
    )
}

function ProfileStackScreen() {
    return (
        <ProfileStack.Navigator>
            <ProfileStack.Screen name="Home" component={Home} />
        </ProfileStack.Navigator>
    )
}

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Home" component={ProfileStackScreen} />
        <Tab.Screen name="Settings" component={SettingsStackScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

Things I have tried:

Accessing the options of the function and hiding that way.

Passing tabBarVisible as a prop to the Screen.

What I am asking for is, what is the correct way of hiding tabs on screens in React Navigation v5.

Body:
Let's suppose that you want to hide tabs when you are entering Settings. Just add navigation in your constructor:

function SettingsStackScreen({ navigation }) {
    navigation.setOptions({ tabBarVisible: false })
    return (
        <SettingsStack.Navigator>
            <SettingsStack.Screen name="Settings" component={SettingsScreen} />
        </SettingsStack.Navigator>
    )
}

This code should work.


问:
Window.open - Override browser window tab
Let's say I have two web apps.

In my first web app, there is a button that uses window.open and when a user clicks that button it opens a new tab with a new url link. When it opens the new tab, it puts a target name to that tab.

For example, window.open(url, "foo");
The new tab opens the url with the target name "foo".

Now, I have a second web app and this one also has a button that uses window.open. If a user clicks this button, I want to override any tab with name "foo" whether the tab was opened from the first web app or second web app.

In the second web app, it uses window.open(url, "foo") as well. Exactly the same code as the first web app.

The problem is that the tab is only replaced when it is created from the same web app. If a user clicks the button and create a new tab from the first web app and the user clicks the button from second web app, rather it overrides the tab from the first web app but it creates another new tab although the target name is same.

Is there any way that I can override any tab that has target name?

答:
No, and this is a security feature.

I can't find a reference link, but an additional requirement for window reuse is that the window.opener attribute must be the same.

So, for example, if you had two links like these:

Foo on Wikipedia
Bar on Wikipedia
```

<p>then clicking on each one would re-use the same window, because the target is the same and because the window containing the links matches the value of <code>window.opener</code> on the target window.</p>

<p>If you added <code>rel="noopener"</code> to the links like this:</p>

<pre class="lang-html prettyprint-override"><code>Foo on Wikipedia
Bar on Wikipedia
</code>```

then the window would not be re-used (even though the target matches) because the value of window.opener would not match the origin window.

Body:
No, and this is a security feature.

I can't find a reference link, but an additional requirement for window reuse is that the window.opener attribute must be the same.

So, for example, if you had two links like these:

<a href="https://en.wikipedia.org/wiki/Foo" target="foo">Foo on Wikipedia</a>
<a href="https://en.wikipedia.org/wiki/Bar" target="foo">Bar on Wikipedia</a>

then clicking on each one would re-use the same window, because the target is the same and because the window containing the links matches the value of window.opener on the target window.

If you added rel="noopener" to the links like this:

<a href="https://en.wikipedia.org/wiki/Foo" target="foo" rel="noopener">Foo on Wikipedia</a>
<a href="https://en.wikipedia.org/wiki/Bar" target="foo" rel="noopener">Bar on Wikipedia</a>

then the window would not be re-used (even though the target matches) because the value of window.opener would not match the origin window.


问:
How to remove space between bootstrap 4 column
how to remove spacing between bootstrap   columns ? bellow i have three bootstrap columns but whenever i try to remove space between them  it is not working as it was expected

<!doctype html>

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

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css" rel="stylesheet">

      <link href="phcoding.css" type="text/css" rel="stylesheet">
          <title>delinahproducts</title>

                lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

                lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

                lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

   ```

答:
Why auto margin, try:

.col-md-3 {
 margin:0!important;
 padding:0!important;
}```


问:
TypeError: $(...).tooltip is not a function with webpack
I'm trying to migrate my application from requirejs to webpack 2 but i'm having trouble.

My webpack config :

```<code> rules: [
            // rules for modules (configure loaders, parser options, etc.)

            {
                test: /\.jsx?$/,
                include: [
                    path.resolve(__dirname, "src")
                ],
                exclude: [
                    path.resolve(__dirname, "app/demo-files")
                ],

                enforce: "pre",
                enforce: "post",

            },

            {
                test: /underscore/,
                loader: 'expose-loader?_'
            },
            {
                test: /howler/,
                loader: 'expose-loader?Howl'
            },
            {
                test: /pathfinding/,
                loader: 'expose-loader?PF'
            },
            {
                test: /stats/,
                loader: 'expose-loader?Stats'
            },
            {
                test: /datgui/,
                loader: 'expose-loader?dat.gui'
            },
            { test: /jquery/,
                loader: 'imports?jQuery=jquery,$=jquery,this=>window'
            },
            {
                test: /jquery-ui/,
                use: [
                    'expose-loader?$',
                    'imports-loader?this=>window,jquery'
                ]
            }
</code>```

And in plugin section :

```<code>plugins: [
            new webpack.ProvidePlugin({
                "$":"libs/jquery/jquery.min",
                "jQuery":"libs/jquery/jquery.min",
                "window.jQuery":"libs/jquery/jquery.min"
            }),
        ]
</code>```

But when i do this i have the following error :

```<code>Game.js:48 Uncaught TypeError: $(...).tooltip is not a function
    at Game.init (Game.js:48)
    at Object.<anonymous> (init.js:6)
    at Object.<anonymous> (init.js:7)
    at __webpack_require__ (bootstrap aa1ecbe…:678)
</code>```

Can you help me with this trouble ? I think the problem is with the import of jquery but i don't know how to resolve the issue...

Thanks

答:
Try adding

```<code>Popper: ['popper.js', 'default']
</code>```

To your plugins

Body:
I'm trying to migrate my application from requirejs to webpack 2 but i'm having trouble.

My webpack config :

 rules: [
            // rules for modules (configure loaders, parser options, etc.)

            {
                test: /\.jsx?$/,
                include: [
                    path.resolve(__dirname, "src")
                ],
                exclude: [
                    path.resolve(__dirname, "app/demo-files")
                ],

                enforce: "pre",
                enforce: "post",

            },

            {
                test: /underscore/,
                loader: 'expose-loader?_'
            },
            {
                test: /howler/,
                loader: 'expose-loader?Howl'
            },
            {
                test: /pathfinding/,
                loader: 'expose-loader?PF'
            },
            {
                test: /stats/,
                loader: 'expose-loader?Stats'
            },
            {
                test: /datgui/,
                loader: 'expose-loader?dat.gui'
            },
            { test: /jquery/,
                loader: 'imports?jQuery=jquery,$=jquery,this=>window'
            },
            {
                test: /jquery-ui/,
                use: [
                    'expose-loader?$',
                    'imports-loader?this=>window,jquery'
                ]
            }

And in plugin section :

plugins: [
            new webpack.ProvidePlugin({
                "$":"libs/jquery/jquery.min",
                "jQuery":"libs/jquery/jquery.min",
                "window.jQuery":"libs/jquery/jquery.min"
            }),
        ]

But when i do this i have the following error :

Game.js:48 Uncaught TypeError: $(...).tooltip is not a function
    at Game.init (Game.js:48)
    at Object.<anonymous> (init.js:6)
    at Object.<anonymous> (init.js:7)
    at __webpack_require__ (bootstrap aa1ecbe…:678)

Can you help me with this trouble ? I think the problem is with the import of jquery but i don't know how to resolve the issue...

Thanks

Body:
Try adding

Popper: ['popper.js', 'default']

To your plugins


问:
VS Code DevTools Dark Theme has black console text on dark backgrounds
I switched the Chrome/Electron DevTools Theme to Dark (in the DevTools Settings, under Preferences), so that it doesn't glare late at night.

But the console text is rendered black still, which is difficult to read on the dark backgrounds for Errors or Warnings:

Is there a setting for the DevTools themselves that I should look into, or is this an Issue I should raise in VS Code? Or Electron?

答:
I'm unsure when, but it's been fixed.  Here is Code 1.42

Thank you.