问:
C++ Vector Push_back producing Weird Side Effect
While I was using STL vector to store class objects,, I observed a very weird side effect, where push_back method modifies the Existing Data!

Basically I have a class containing several fields as follows:

```<code>class MyClass {
    MyClass(std::string s, int i) {
        StringValue = s;
        IntValue = i;
    }

    std::string StringValue;
    int IntValue;
}
</code>```

I have a vector that contains the POINTERS to MyClass objects.. and then I am basically pushing back references to objects:

```<code>std::vector<MyClass*> MyVector;
MyClass c1("CLASS 1", 1);
MyClass c2("CLASS 2", 2);

MyVector.push_back(&c1);
// Result:
// *MyVector[0]    ==>    ("Class 1", 1)

MyVector.push_back(&c2);
// Result:
// *MyVector[0]    ==>    ("Class 2", 2)   ??why 2??
// *MyVector[1]    ==>    ("Class 2", 2)
</code>```

Do you see the strange result that I got??  I've set breakpoints after each push_back statement,,, and this weird thing happened.

The first push_back statement worked fine. But then the second push_back statement MODIFIED the content of the first element, which doesn't make sense to me..

I'm assuming that it has something to do with me storing References instead of actual objects inside the vector.... but I can't figure out what is wrong.

How can I handle this issue? Any insights?

Thanks

UPDATE:

(simplified code)

```<code>MyClass c1("CLASS 1", 1);
MyClass c2("CLASS 2", 2);

MyClass temp;
while (int i=0; i<2; i++) {
    temp = c1;
    MyVector.push_back(temp);
}
</code>```

You guys are right,, I get what I'm doing wrong here.. The actual object gets destructed in every loop..   What's the best way to fix this while keeping the current structure??  I'ts hard to explain but I would like to keep this structure (keeping temporary buffer outside the loop).. is this possible?

答:
For anyone looking for a clear and concise explanation:

Why does an object get destroyed when pushing it to a vector?

You are creating a temporary object:

```<code>m_foos.push_back(Foo(a));
//               ^^^^^^
</code>```

Solution:
The function emplace_back is what you want to use:

```<code>m_foos.emplace_back(a);
</code>```

Check out: push_back vs emplace_back

EDIT---
Also, I noted that when compiling with CLion, the error is not fixed. It is also known to be an error on Visual Studio. In other words, be careful with your IDE.

Body:
While I was using STL vector to store class objects,, I observed a very weird side effect, where push_back method modifies the Existing Data!

Basically I have a class containing several fields as follows:

class MyClass {
    MyClass(std::string s, int i) {
        StringValue = s;
        IntValue = i;
    }

    std::string StringValue;
    int IntValue;
}

I have a vector that contains the POINTERS to MyClass objects.. and then I am basically pushing back references to objects:

std::vector<MyClass*> MyVector;
MyClass c1("CLASS 1", 1);
MyClass c2("CLASS 2", 2);

MyVector.push_back(&c1);
// Result:
// *MyVector[0]    ==>    ("Class 1", 1)

MyVector.push_back(&c2);
// Result:
// *MyVector[0]    ==>    ("Class 2", 2)   ??why 2??
// *MyVector[1]    ==>    ("Class 2", 2)

Do you see the strange result that I got??  I've set breakpoints after each push_back statement,,, and this weird thing happened.

The first push_back statement worked fine. But then the second push_back statement MODIFIED the content of the first element, which doesn't make sense to me..

I'm assuming that it has something to do with me storing References instead of actual objects inside the vector.... but I can't figure out what is wrong.

How can I handle this issue? Any insights?

Thanks

UPDATE:

(simplified code)

MyClass c1("CLASS 1", 1);
MyClass c2("CLASS 2", 2);

MyClass temp;
while (int i=0; i<2; i++) {
    temp = c1;
    MyVector.push_back(temp);
}

You guys are right,, I get what I'm doing wrong here.. The actual object gets destructed in every loop..   What's the best way to fix this while keeping the current structure??  I'ts hard to explain but I would like to keep this structure (keeping temporary buffer outside the loop).. is this possible?

Body:
For anyone looking for a clear and concise explanation:

Why does an object get destroyed when pushing it to a vector?

You are creating a temporary object:

m_foos.push_back(Foo(a));
//               ^^^^^^

Solution:
The function emplace_back is what you want to use:

m_foos.emplace_back(a);

Check out: push_back vs emplace_back

EDIT---
Also, I noted that when compiling with CLion, the error is not fixed. It is also known to be an error on Visual Studio. In other words, be careful with your IDE.


来源: stackexchange

问:
Pipx installation Problem / eth-brownie installation error
Someone please help me with this error

after installing pipx successfully - $ python3 -m pip install --user pipx &&
$ python3 -m pipx ensurepath

Successfully installed pipx-0.16.4

when i run this command - $ pipx install eth-brownie

I'm getting this error - $ bash: pipx: command not found

答: Try using pip3 install eth-brownie. Worked for me</p>

ContentLicense: CC BY-SA 4.0


问:
Handling action in Remix.run without POST
I read up on the Remix docs on action and most of information I can find on action is it uses the the form POST with button submit to trigger the action

```<code>export default function Game() {
    const counter = useLoaderData();

    return (
        <>
            <div>{counter}</div>
            <div>
                <Form method="post">
                    <button type="submit">click</button>
                </Form>
            </div>
        </>
    );
}
</code>```

However, how would the action  be triggered in regards to something else like... drag and drop components, where after dropping it should trigger the action post

答:
useSubmit should do what you want.

An example from the docs

```<code>import { useSubmit, useTransition } from "remix";

export async function loader() {
  await getUserPreferences();
}

export async function action({ request }) {
  await updatePreferences(await request.formData());
  return redirect("/prefs");
}

function UserPreferences() {
  const submit = useSubmit();
  const transition = useTransition();

  function handleChange(event) {
    submit(event.currentTarget, { replace: true });
  }

  return (
    <Form method="post" onChange={handleChange}>
      <label>
        <input type="checkbox" name="darkMode" value="on" />{" "}
        Dark Mode
      </label>
      {transition.state === "submitting" ? (
        <p>Saving...</p>
      ) : null}
    </Form>
  );
}
</code>```

Body:
I read up on the Remix docs on action and most of information I can find on action is it uses the the form POST with button submit to trigger the action

export default function Game() {
    const counter = useLoaderData();

    return (
        <>

{counter}

                <Form method="post">
                    <button type="submit">click</button>
                </Form>

        </>
    );
}

However, how would the action  be triggered in regards to something else like... drag and drop components, where after dropping it should trigger the action post

Body:
useSubmit should do what you want.

An example from the docs

import { useSubmit, useTransition } from "remix";

export async function loader() {
  await getUserPreferences();
}

export async function action({ request }) {
  await updatePreferences(await request.formData());
  return redirect("/prefs");
}

function UserPreferences() {
  const submit = useSubmit();
  const transition = useTransition();

  function handleChange(event) {
    submit(event.currentTarget, { replace: true });
  }

  return (
    <Form method="post" onChange={handleChange}>
      <label>
        <input type="checkbox" name="darkMode" value="on" />{" "}
        Dark Mode
      </label>
      {transition.state === "submitting" ? (
        <p>Saving...</p>
      ) : null}
    </Form>
  );
}


问:
What is this Kotlin type: (String..String?)
IntelliJ is showing me context hints that my variables are of type (String..String?). I cannot find any mention of it on the internet, what is this type?

答:
(String..String?) represents a flexible type with lower bound String and upperbound String? (nullable string). This is not valid Kotlin code (it's not denotable) but it is used in the compiler internals and thus in IntelliJ's hints sometimes.

(On the JVM we often see platform types using ! as in String!, which are a more specific case of flexible types)

It's Kotlin's way of saying it doesn't know whether the String type declared for payload.email is nullable or not (for instance if this is declared in Java, which doesn't distinguish those), and yet it doesn't want to enforce either of those, for convenience (hence "flexible").

As the name suggests, flexible types are flexible — a value of type (L..U) can be used in any context, where one of the possible types between L and U is needed

This means that even though the actual type of the value is "somewhere between String and String?", values of this type can be used even in places expecting String, even though the real type of that value may be String? and thus the value could be null.

This is useful because assuming it is String would mean that null checks would be marked as redundant, and assuming it is String? would force the developer to write null checks everywhere, even though they might know that this particular Java method cannot return null.

In general, it's a good practice to explicitly declare the type of a variable that you get from Java, to avoid the propagation of the platform type and the uncertainty (and unsafety) that comes with it:

val email: String = payload.email // if you know it cannot be null
val email: String? = payload.email // if you don't know
```


问:
How to split a Text node to sub Text node with specified length?
I want to do something similar to splitText(), but with length, so if I have a Text node that contains the following string for example:

```<code>Hello please get *me* as a text node
</code>```

Then only get *me* as a new Text node.

splitText() just splits into two so that's not working

答:
You can use the normal String.split method, which is more straight forward if you know you want to split on the asterisk.

const textNode = document.body.firstChild
const text = textNode.data.split("*")[1]
const newTextNode = document.createTextNode(text)
document.querySelector("strong").append(newTextNode)```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Hello please get *me* as a text node
<br> new textNode: <strong><strong></code>```

You can also use substring.

const textNode = document.body.firstChild
const text = textNode.data.substring(22, 26)
const newTextNode = document.createTextNode(text)
document.querySelector("strong").append(newTextNode)```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Hello please get *me* as a text node
<br> new textNode: <strong><strong></code>```

Body:
I want to do something similar to splitText(), but with length, so if I have a Text node that contains the following string for example:

Hello please get *me* as a text node

Then only get *me* as a new Text node.

splitText() just splits into two so that's not working

Body:
You can use the normal String.split method, which is more straight forward if you know you want to split on the asterisk.

const textNode = document.body.firstChild
const text = textNode.data.split("*")[1]
const newTextNode = document.createTextNode(text)
document.querySelector("strong").append(newTextNode)

Hello please get *me* as a text node
<br> new textNode: <strong><strong>

You can also use substring.

const textNode = document.body.firstChild
const text = textNode.data.substring(22, 26)
const newTextNode = document.createTextNode(text)
document.querySelector("strong").append(newTextNode)

Hello please get *me* as a text node
<br> new textNode: <strong><strong>


问:
SwiftUI Map Change Region Programmatically to Show Any Annotations Added
I'm trying to use the new Map in SwiftUI. I would like to change the visible region
programmatically to include all of the annotations that are added programmatically,
similar to the way you can show a bounding box for a route overlay in the older UIMap.
I have not found anything in the documentation to do this. I created my own approach
by getting the min/max values for the latitude and longitude of each annotation and
then creating a center for the new region and a span. Both of these involve some math.
My result works for my North America location, but I will need to add significant
complexity to handle the cases where the annotation area encompasses the equator, the
date line or the prime meridian. Before I do so, I'm hoping someone has a solution
that I have missed.

Here is my solution:

```<code>struct MyMapView: View {
    @StateObject var myMapVM = MyMapViewModel()

    var body: some View {
        VStack {
            let m = Map(coordinateRegion: $myMapVM.region, annotationItems: myMapVM.centers) { site in

                MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: site.lat, longitude: site.long)) {
                    GroupAnnotationPinView(title: site.name)
                        .onTapGesture {
                            openMapWithCoordinate(coordinate: CLLocationCoordinate2D(latitude: site.lat, longitude: site.long), name: site.name)
                        }//on tap
                }//map annotation
            }//map
            m.onAppear {
                //this works, so reference to Map seems to work ok
                //print(m.body)
            }

            Button(action: {
                myMapVM.createCoordinateRegion()
            }, label: {
                Image(systemName: "square.and.pencil")
                    .resizable()
                    .frame(width: 44, height: 44)
                    .padding()
            })
                .padding(.bottom, 20)
        }//v
        .ignoresSafeArea()
    }//body

    func openMapWithCoordinate(coordinate: CLLocationCoordinate2D, name: String) {
        let place = MKPlacemark(coordinate: coordinate)
        let mapItem = MKMapItem(placemark: place)
        mapItem.name = name
        mapItem.openInMaps(launchOptions: nil)
    }//open
}//my map view

struct GroupAnnotationPinView: View {
    @State private var showTitle = true
    let title: String
    var body: some View {
        VStack(spacing: 0) {
            Image(systemName: "mappin")
                .font(.title)
                .foregroundColor(.red)
        }//v
    }//body
}//group anno view
</code>```

And the View Model

```<code>class MyMapViewModel: ObservableObject {

    @Published var annotations: [MKAnnotation] = []
    @Published var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 37.334_900,
                                       longitude: -122.009_020),
        latitudinalMeters: 10000,
        longitudinalMeters: 10000
    )

    let centers: [Center] = [
        .init(name: "One", lat: 37.334, long: -122.009),
        .init(name: "Two", lat: 37.380, long: -122.010),
        .init(name: "Three", lat: 37.400, long: -122.010),
        .init(name: "Four", lat: 40.000, long: -120.000)
            //.init(name: "Four", lat: 37.600, long: -121.800)
        ]

    func createCoordinateRegion() {

        //you need to fix this to account for dateline, prime meridian and equator in span

        let maxX = centers.max(\.lat)
        let maxY = centers.max(\.long)
        let minX = centers.min(\.lat)
        let minY = centers.min(\.long)
        //print("minX.lat is ", minX?.lat ?? "nil")
        //print("maxX.lat is ", maxX?.lat ?? "nil")
        //print("minY.long is ", minY?.long ?? "nil")
        //print("maxY.long is ", maxY?.long ?? "nil")

        guard let minXS = minX?.lat, let maxXS = maxX?.lat, let minYS = minY?.long, let maxYS = maxY?.long else { return }

        let deltaX = maxXS - minXS
        let deltaY = maxYS - minYS

        let newCenterLat = minXS + deltaX / 2
        let newCenterLong = maxYS - abs(deltaY / 2)
        //print(newCenterLat)
        //print(newCenterLong)

        let newRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: newCenterLat, longitude: newCenterLong), span: MKCoordinateSpan(latitudeDelta: max(deltaX, deltaY), longitudeDelta: max(deltaX, deltaY)))

        region = newRegion

    }//create coord region

}//class

extension Sequence {
    func max<T: Comparable>(_ predicate: (Element) -> T)  -> Element? {
        self.max(by: { predicate($0) < predicate($1) })
    }
    func min<T: Comparable>(_ predicate: (Element) -> T)  -> Element? {
        self.min(by: { predicate($0) < predicate($1) })
    }
}// ext seq

struct Center: Identifiable, Hashable {
    let id = UUID()
    let name: String
    let lat: Double
    let long: Double
}//center
</code>```

Any guidance would be appreciated: Xcode 13.2.1 iOS 15.2

答:
I do this by converting each annotation coordinate to an MKMapRect:

```<code>let rect = MKMapRect(origin: MKMapPoint(coordinate), size: MKMapSize(width: 0, height: 0))
</code>```

MKMapRect is able to calculate a union and knows how to handle the 180th Meridian (see method spans180thMeridian:

```<code>private(set) var union: MKMapRect? = nil
func union(_ rect: MKMapRect) {
    guard let union = self.union else {
        self.union = rect
        return
    }
    self.union = union.union(rect)
}
</code>```

After you're done, you can convert it into a region and use it:

```<code>let region = MKCoordinateRegion(union)
</code>```

Be aware that this cuts the AnnotationViews at the edge in half, so you have to calculate some space around it.

Alternative solution:
This is one of MANY reasons to prefer the old MKMapKit where you just call

```<code>mapView.showAnnotations(specificAnnotations, animated: true)
</code>```

This changes the region to show specificAnnotations while keeping the other annotations on the map and not cutting AnnotationViews in half.

Body:
I'm trying to use the new Map in SwiftUI. I would like to change the visible region
programmatically to include all of the annotations that are added programmatically,
similar to the way you can show a bounding box for a route overlay in the older UIMap.
I have not found anything in the documentation to do this. I created my own approach
by getting the min/max values for the latitude and longitude of each annotation and
then creating a center for the new region and a span. Both of these involve some math.
My result works for my North America location, but I will need to add significant
complexity to handle the cases where the annotation area encompasses the equator, the
date line or the prime meridian. Before I do so, I'm hoping someone has a solution
that I have missed.

Here is my solution:

struct MyMapView: View {
    @StateObject var myMapVM = MyMapViewModel()

    var body: some View {
        VStack {
            let m = Map(coordinateRegion: $myMapVM.region, annotationItems: myMapVM.centers) { site in

                MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: site.lat, longitude: site.long)) {
                    GroupAnnotationPinView(title: site.name)
                        .onTapGesture {
                            openMapWithCoordinate(coordinate: CLLocationCoordinate2D(latitude: site.lat, longitude: site.long), name: site.name)
                        }//on tap
                }//map annotation
            }//map
            m.onAppear {
                //this works, so reference to Map seems to work ok
                //print(m.body)
            }

            Button(action: {
                myMapVM.createCoordinateRegion()
            }, label: {
                Image(systemName: "square.and.pencil")
                    .resizable()
                    .frame(width: 44, height: 44)
                    .padding()
            })
                .padding(.bottom, 20)
        }//v
        .ignoresSafeArea()
    }//body

    func openMapWithCoordinate(coordinate: CLLocationCoordinate2D, name: String) {
        let place = MKPlacemark(coordinate: coordinate)
        let mapItem = MKMapItem(placemark: place)
        mapItem.name = name
        mapItem.openInMaps(launchOptions: nil)
    }//open
}//my map view

struct GroupAnnotationPinView: View {
    @State private var showTitle = true
    let title: String
    var body: some View {
        VStack(spacing: 0) {
            Image(systemName: "mappin")
                .font(.title)
                .foregroundColor(.red)
        }//v
    }//body
}//group anno view

And the View Model

class MyMapViewModel: ObservableObject {

    @Published var annotations: [MKAnnotation] = []
    @Published var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 37.334_900,
                                       longitude: -122.009_020),
        latitudinalMeters: 10000,
        longitudinalMeters: 10000
    )

    let centers: [Center] = [
        .init(name: "One", lat: 37.334, long: -122.009),
        .init(name: "Two", lat: 37.380, long: -122.010),
        .init(name: "Three", lat: 37.400, long: -122.010),
        .init(name: "Four", lat: 40.000, long: -120.000)
            //.init(name: "Four", lat: 37.600, long: -121.800)
        ]

    func createCoordinateRegion() {

        //you need to fix this to account for dateline, prime meridian and equator in span

        let maxX = centers.max(\.lat)
        let maxY = centers.max(\.long)
        let minX = centers.min(\.lat)
        let minY = centers.min(\.long)
        //print("minX.lat is ", minX?.lat ?? "nil")
        //print("maxX.lat is ", maxX?.lat ?? "nil")
        //print("minY.long is ", minY?.long ?? "nil")
        //print("maxY.long is ", maxY?.long ?? "nil")

        guard let minXS = minX?.lat, let maxXS = maxX?.lat, let minYS = minY?.long, let maxYS = maxY?.long else { return }

        let deltaX = maxXS - minXS
        let deltaY = maxYS - minYS

        let newCenterLat = minXS + deltaX / 2
        let newCenterLong = maxYS - abs(deltaY / 2)
        //print(newCenterLat)
        //print(newCenterLong)

        let newRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: newCenterLat, longitude: newCenterLong), span: MKCoordinateSpan(latitudeDelta: max(deltaX, deltaY), longitudeDelta: max(deltaX, deltaY)))

        region = newRegion

    }//create coord region

}//class

extension Sequence {
    func max<T: Comparable>(_ predicate: (Element) -> T)  -> Element? {
        self.max(by: { predicate($0) < predicate($1) })
    }
    func min<T: Comparable>(_ predicate: (Element) -> T)  -> Element? {
        self.min(by: { predicate($0) < predicate($1) })
    }
}// ext seq

struct Center: Identifiable, Hashable {
    let id = UUID()
    let name: String
    let lat: Double
    let long: Double
}//center

Any guidance would be appreciated: Xcode 13.2.1 iOS 15.2

Body:
I do this by converting each annotation coordinate to an MKMapRect:

let rect = MKMapRect(origin: MKMapPoint(coordinate), size: MKMapSize(width: 0, height: 0))

MKMapRect is able to calculate a union and knows how to handle the 180th Meridian (see method spans180thMeridian:

private(set) var union: MKMapRect? = nil
func union(_ rect: MKMapRect) {
    guard let union = self.union else {
        self.union = rect
        return
    }
    self.union = union.union(rect)
}

After you're done, you can convert it into a region and use it:

let region = MKCoordinateRegion(union)

Be aware that this cuts the AnnotationViews at the edge in half, so you have to calculate some space around it.

Alternative solution:
This is one of MANY reasons to prefer the old MKMapKit where you just call

mapView.showAnnotations(specificAnnotations, animated: true)

This changes the region to show specificAnnotations while keeping the other annotations on the map and not cutting AnnotationViews in half.


问:
Best Way to Add Syntax Highlighting to Code Block - React Sanity Blog
I am trying to find the most efficient way to add syntax highlighting to my react sanity.io blog. Here's the article component that I created using react:

import React, {useEffect, useState} from "react";
import {useParams} from "react-router-dom";
import sanityClient from "../../client";
import BlockContent from "@sanity/block-content-to-react";
import imageUrlBuilder from "@sanity/image-url";

import Prism from "prismjs";

const builder = imageUrlBuilder(sanityClient);
function urlFor(source) {
  return builder.image(source);
}

const serializers = {
  types: {
    code: (props) => (

        {props.node.code}
      ```
    ),
  },
};

export default function SinglePost() {
  const [postData, setPostData] = useState(null);
  const {slug} = useParams();

  useEffect(() => {
    sanityClient
      .fetch(
        `*[slug.current == $slug]{
          title,
          slug,
          mainImage{
            asset->{
              _id,
              url
             }
           },
         body,
        "name": author->name,
        "authorImage": author->image
       }`,
        {slug}
      )
      .then((data) => setPostData(data[0]))
      .catch(console.error);

    Prism.highlightAll();
  }, [slug]);

  if (!postData) return <div>Loading...</div>;

  return (
    <article>
      <h2>{postData.title}</h2>
      <div>
        <img
          src={urlFor(postData.authorImage).width(100).url()}
          alt="Author is Kap"
        />
        <h4>{postData.name}</h4>
      </div>

      <img src={urlFor(postData.mainImage).width(200).url()} alt="" />
      <div>
        <BlockContent
          blocks={postData.body}
          projectId={sanityClient.clientConfig.projectId}
          dataset={sanityClient.clientConfig.dataset}
          serializers={serializers}
        />
      </div>
    </article>
  );
}</code>```

I am importing article data from Sanity and rendering it as a component. I tried using prism.js but I am having issues getting it to work.

What's the best and most efficient way to to enable syntax highlighting?

答: Well, I'd use react-syntax-highlighter package on NPM. It's pretty easy to add to your project. Basically a plug-and-play. With no awkward configurations.</p>

Body:
I am trying to find the most efficient way to add syntax highlighting to my react sanity.io blog. Here's the article component that I created using react:

import React, {useEffect, useState} from "react";
import {useParams} from "react-router-dom";
import sanityClient from "../../client";
import BlockContent from "@sanity/block-content-to-react";
import imageUrlBuilder from "@sanity/image-url";

import Prism from "prismjs";

const builder = imageUrlBuilder(sanityClient);
function urlFor(source) {
  return builder.image(source);
}

const serializers = {
  types: {
    code: (props) => (

        {props.node.code}

    ),
  },
};

export default function SinglePost() {
  const [postData, setPostData] = useState(null);
  const {slug} = useParams();

  useEffect(() => {
    sanityClient
      .fetch(
        `*[slug.current == $slug]{
          title,
          slug,
          mainImage{
            asset->{
              _id,
              url
             }
           },
         body,
        "name": author->name,
        "authorImage": author->image
       }`,
        {slug}
      )
      .then((data) => setPostData(data[0]))
      .catch(console.error);

    Prism.highlightAll();
  }, [slug]);

  if (!postData) return
Loading...
;

  return (

{postData.title}

{postData.name}

        <BlockContent
          blocks={postData.body}
          projectId={sanityClient.clientConfig.projectId}
          dataset={sanityClient.clientConfig.dataset}
          serializers={serializers}
        />

  );
}

I am importing article data from Sanity and rendering it as a component. I tried using prism.js but I am having issues getting it to work.

What's the best and most efficient way to to enable syntax highlighting?


问:
I'm trying to print one letter after another
I'm trying to print one letter after another but this code just waits 100ms and then prints the value with no pauses. Any idea why this happens and how to fix it?
Code:</p>
```<code>    for (let i = 0; i < welcText.length; i++) {
        setTimeout(()=>{
            welcome.innerText += welcText[i];
        },100);
    }
</code>```

答:
The following function divtxt() returns a Promise. You can use it to send a txt to a div with a given id and let each letter appear in ms intervals. AND: you can build a chain of any number of follow-up actions with it:

function divtxt(id, txt, ms, wait = 0) {
  const div = document.getElementById(id);
  return new Promise((res, rej) => {
    setTimeout(() => { // optional initial timeout, when wait>0
      div.textContent = "";
      const a = txt.split(""),
        iv = setInterval(() => {
          if (a.length)
            div.textContent += a.shift();
          else {
            clearInterval(iv);
            res(txt);
          }
        }, ms);
    }, wait);
  });
}
divtxt("welcome", "Hello world, this is my way of doing it! ", 100)
  .then(prevText => (console.log(prevText + ' is done.'),
    divtxt("descr", "You can also chain this function with any number of consecutive actions."
    +" Now: wait for 2 seconds ...", 100)))
  .then(() => divtxt("welcome", "This promised-based approach REALLY lets you do it!! ", 50, 2000))
  .then(() => (console.log("ready?"),"Yes! I am REALLY DONE now! "))
  .then(console.log)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#welcome {
  font-weight: 900
}</code>```

```

Body:
I'm trying to print one letter after another but this code just waits 100ms and then prints the value with no pauses. Any idea why this happens and how to fix it?
Code:

    for (let i = 0; i < welcText.length; i++) {
        setTimeout(()=>{
            welcome.innerText += welcText[i];
        },100);
    }

Body:
The following function divtxt() returns a Promise. You can use it to send a txt to a div with a given id and let each letter appear in ms intervals. AND: you can build a chain of any number of follow-up actions with it:

function divtxt(id, txt, ms, wait = 0) {
  const div = document.getElementById(id);
  return new Promise((res, rej) => {
    setTimeout(() => { // optional initial timeout, when wait>0
      div.textContent = "";
      const a = txt.split(""),
        iv = setInterval(() => {
          if (a.length)
            div.textContent += a.shift();
          else {
            clearInterval(iv);
            res(txt);
          }
        }, ms);
    }, wait);
  });
}
divtxt("welcome", "Hello world, this is my way of doing it! ", 100)
  .then(prevText => (console.log(prevText + ' is done.'),
    divtxt("descr", "You can also chain this function with any number of consecutive actions."
    +" Now: wait for 2 seconds ...", 100)))
  .then(() => divtxt("welcome", "This promised-based approach REALLY lets you do it!! ", 50, 2000))
  .then(() => (console.log("ready?"),"Yes! I am REALLY DONE now! "))
  .then(console.log)

#welcome {
  font-weight: 900
}

<div id="welcome"></div>
<div id="descr"></div>


问:
CSS problem, 100% width keeps moving out of position
I'm currently working on this website,
http://no-illusions.nl
It's going fine but I found a pretty stupid thing that I can't resolve.

I have an div (wrapper) with an width of 500px and inside I have different div's containing images and text. Now the problem is that the text is dynamic in width, on some parts it could be 200px width and on some pages it could be 350px.

So I put the width on 100% but now the part just floats underneath where I want it!

This is how it should look,
![how it should look][1]

But this is how it looks,

I hope you guys can give me a push in the right direction.

答: This has troubled me before and I usually solve it by setting the paragraph's max-width. That should cause the text to wrap within that width. </p>

ContentLicense: CC BY-SA 3.0


问:
Comparing two exact videos using opencv python
My objective is to determine similarity between two exact same videos. My approach is a bit naive i.e. to compare them frame by frame and see if two frame exactly matches or not. I am using the following python code for this:

```<code>import cv2
import numpy as np

capture = cv2.VideoCapture("video.wmv")
capture2 = cv2.VideoCapture("video.wmv")
counter = 0
while True:
    f, frame = capture.read()
    f2, frame2 = capture2.read()
    frame = cv2.GaussianBlur(frame,(15,15),0)
    frame2 = cv2.GaussianBlur(frame2, (15, 15), 0)
    try:
        res = frame - frame2
        if(np.count_nonzero(res) > 0 ):
            counter += 1
        else: continue
    except:
        print(counter)
</code>```

The total number of frames in my video is around 600K. The code runs for almost 20K frames with exact matches and the counter remains zero (i.e. exact frame matching) but after 20K frames it started returning the following exception for all frames to come

```<code>unsupported operand type(s) for -: 'NoneType' and 'NoneType'
</code>```

From the exception I understand that it is not reading any frames that is why returning a NonType. Please guide me whether my approach for comparing videos is correct (I know it is not efficient way). Also why I am getting this error ?

答:
You didn't break your while loop. And it continued reading the frames even when the vidoes had finished, hence returning a NoneType object.
You can try:</p>
```<code>while True:
f, frame = capture.read()
f2, frame2 = capture2.read()
if not f and not f2:
    break
frame = cv2.GaussianBlur(frame,(15,15),0)
frame2 = cv2.GaussianBlur(frame2, (15, 15), 0)
try:
    res = frame - frame2
    if(np.count_nonzero(res) > 0 ):
        counter += 1
    else: continue
except:
    print(counter)
</code>```

Body:
My objective is to determine similarity between two exact same videos. My approach is a bit naive i.e. to compare them frame by frame and see if two frame exactly matches or not. I am using the following python code for this:

import cv2
import numpy as np

capture = cv2.VideoCapture("video.wmv")
capture2 = cv2.VideoCapture("video.wmv")
counter = 0
while True:
    f, frame = capture.read()
    f2, frame2 = capture2.read()
    frame = cv2.GaussianBlur(frame,(15,15),0)
    frame2 = cv2.GaussianBlur(frame2, (15, 15), 0)
    try:
        res = frame - frame2
        if(np.count_nonzero(res) > 0 ):
            counter += 1
        else: continue
    except:
        print(counter)

The total number of frames in my video is around 600K. The code runs for almost 20K frames with exact matches and the counter remains zero (i.e. exact frame matching) but after 20K frames it started returning the following exception for all frames to come

unsupported operand type(s) for -: 'NoneType' and 'NoneType'

From the exception I understand that it is not reading any frames that is why returning a NonType. Please guide me whether my approach for comparing videos is correct (I know it is not efficient way). Also why I am getting this error ?

Body:
You didn't break your while loop. And it continued reading the frames even when the vidoes had finished, hence returning a NoneType object.
You can try:

while True:
f, frame = capture.read()
f2, frame2 = capture2.read()
if not f and not f2:
    break
frame = cv2.GaussianBlur(frame,(15,15),0)
frame2 = cv2.GaussianBlur(frame2, (15, 15), 0)
try:
    res = frame - frame2
    if(np.count_nonzero(res) > 0 ):
        counter += 1
    else: continue
except:
    print(counter)


问:
I am getting error "cmdline-tools component is missing" after installing Flutter and Android Studio... I added the Android SDK. How can I solve them?
Android toolchain - I develop for Android devices (Android SDK version 30.0.3):

X cmdline-tools component is missing
  Run `path/to/sdkmanager --install "cmdline-tools;latest"`
  See https://developer.android.com/studio/command-line for more details.
```

答:
If you have already downloaded cmdline-tools and the Android SDK, make sure Flutter isn't looking in the wrong directory with:</p>
```<code>flutter config --android-sdk=""
</code>```

Body:
If you have already downloaded cmdline-tools and the Android SDK, make sure Flutter isn't looking in the wrong directory with:

flutter config --android-sdk=""


问:
My character's horizontal movement is stopping me from using rigidBody2D.AddForce(Vector2.right) or any horizontal axis
I keep trying to Addforce to the left or right but nothing happens. This happened to me in another game before. I just figured out what it was

```<code>rb.velocity = new Vector2(speed * moveX * Time.deltaTime, rb.velocity.y);
</code>```

Here, I'm setting the velocity to 0 if I'm not moving (moveX is Input.GetAxisRaw("Horizontal") )
How do I AddForce horizontally while not having to disable my normal movement? I know I can use transform.Translate but I'd prefer using rb.velocity for now.

答:
With the add force function, link to unity docs below.

https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html

Body:
I keep trying to Addforce to the left or right but nothing happens. This happened to me in another game before. I just figured out what it was

rb.velocity = new Vector2(speed * moveX * Time.deltaTime, rb.velocity.y);

Here, I'm setting the velocity to 0 if I'm not moving (moveX is Input.GetAxisRaw("Horizontal") )
How do I AddForce horizontally while not having to disable my normal movement? I know I can use transform.Translate but I'd prefer using rb.velocity for now.


问:
Median and order statistics with O(n) time complexity
Describe an O(n)-time algorithm that, given a set S of n distinct numbers and a positive
integer k≤n , outputs the k numbers in S that are closest to the median of S (excluding the
median). Hint: The target numbers may not be evenly placed around the median in the sorted
version of the array. E.g., consider 1,2,3,8,10; the 2 numbers closest to the median 3 are 1,2,
excluding the median itself, but they are both less than the median. Note: this is just an
illustration; don't assume that the array is sorted)

Here is the answer that I found link:

Answer: Find the n/2 − k/2 largest element in linear time. Partition on that element. Then, find the k largest element in the bigger subarray formed from the partition. Then, the elements in the smaller subarray from partitioning on this element are the desired k numbers.

My illustration:

Suppose I have an array with 11 elements and the array is an unsorted array

```<code>index_number 1  2  3  4  5  6  7  8  9  10  11
arr_elements 2  5  3  10 4  7  1  12 6  13  8
</code>```

As there are 11 elements median should be 11/2= 5.5 approximately, 6. So arr_element 7 is the median. Now the solution said Find the n/2 − k/2 largest element in linear time. Suppose k=4 so, k/4 = 2, therefore need to find out largest element from index 2 through index 6. The array elements from index 2 through 6 are {5,3,10,4,7}. So the largest element is 10. Now the answer said  Partition on that element. So there will be two sub array after partitioning from arr_element 10. The sub arrays are {2,5,3} and {4,7,1,12,6,13,8}. Then the answer said Then, find the k largest element in the bigger subarray formed from the partition. k=4 so kth largest element means 4th largest element. The 4th largest element in the big subarray is 8. Now, the algorithm said Then, the elements in the smaller subarray from partitioning on this element are the desired k numbers. I did not understand this statement.

The problem came from Cormen's Introduction to algorithm Chapter 9: Median and order statistics

Any hints would be appreciated.

答:
The problem is to find the median, then find the distance d such that exactly k or k+1 points are within that distance from the median, and then output those points.

Hint: Study quickselect.

Body:
Describe an O(n)-time algorithm that, given a set S of n distinct numbers and a positive
integer k≤n , outputs the k numbers in S that are closest to the median of S (excluding the
median). Hint: The target numbers may not be evenly placed around the median in the sorted
version of the array. E.g., consider 1,2,3,8,10; the 2 numbers closest to the median 3 are 1,2,
excluding the median itself, but they are both less than the median. Note: this is just an
illustration; don't assume that the array is sorted)

Here is the answer that I found link:

Answer: Find the n/2 − k/2 largest element in linear time. Partition on that element. Then, find the k largest element in the bigger subarray formed from the partition. Then, the elements in the smaller subarray from partitioning on this element are the desired k numbers.

My illustration:

Suppose I have an array with 11 elements and the array is an unsorted array

index_number 1  2  3  4  5  6  7  8  9  10  11
arr_elements 2  5  3  10 4  7  1  12 6  13  8

As there are 11 elements median should be 11/2= 5.5 approximately, 6. So arr_element 7 is the median. Now the solution said Find the n/2 − k/2 largest element in linear time. Suppose k=4 so, k/4 = 2, therefore need to find out largest element from index 2 through index 6. The array elements from index 2 through 6 are {5,3,10,4,7}. So the largest element is 10. Now the answer said  Partition on that element. So there will be two sub array after partitioning from arr_element 10. The sub arrays are {2,5,3} and {4,7,1,12,6,13,8}. Then the answer said Then, find the k largest element in the bigger subarray formed from the partition. k=4 so kth largest element means 4th largest element. The 4th largest element in the big subarray is 8. Now, the algorithm said Then, the elements in the smaller subarray from partitioning on this element are the desired k numbers. I did not understand this statement.

The problem came from Cormen's Introduction to algorithm Chapter 9: Median and order statistics

Any hints would be appreciated.


问:
git with Beyond Compare (4) on WSL2 Windows 11 not opening the repo version
Trying to get git and Beyond Compare to place nicely together on WSL.  Here is the output from git config --list:

```<code>diff.tool=bc3
difftool.prompt=false
difftool.bc3.path=/mnt/c/Program Files/Beyond Compare 4/BComp.exe
merge.tool=bc3
mergetool.prompt=false
mergetool.bc3.trustexitcode=true
mergetool.bc3.path=/mnt/c/Program Files/Beyond Compare 4/BComp.exe
</code>```

Here is my ~/.gitconfig:

```<code>[diff]
    tool = bc3
[difftool]
    prompt = false
[difftool "bc3"]
    path = /mnt/c/Program Files/Beyond Compare 4/BComp.exe
[merge]
    tool = bc3
[mergetool]
    prompt = false
[mergetool "bc3"]
    trustExitCode = true
    path = /mnt/c/Program Files/Beyond Compare 4/BComp.exe
</code>```

my git --version is:

```<code>git version 2.25.1
</code>```

When I try git difftool file_in_git_repo
Beyond Compare opens with the current version in the left pane, but nothing in the right pane (I have confirmed the file exists in the git repo.)

.git/config has no entries referencing diff or merge

Any suggestions would be most welcome

========================================================================

Similar to VonC's suggestion, I was able to get it working with this in my .gitconfig file (disclaimer - I have not used the mergetool with this new method):

```<code>[diff]
    tool = bc3
[difftool]
    prompt = false
[difftool "bc3"]
    cmd = '/mnt/c/Program Files/Beyond Compare 4/BComp.exe'   \"$(wslpath -aw $LOCAL)\" \"$(wslpath -aw $REMOTE)\"
[merge]
    tool = bc3
[mergetool]
    prompt = false
[mergetool "bc3"]
    trustExitCode = true
    cmd = '/mnt/c/Program Files/Beyond Compare 4/BComp.exe'   \"$(wslpath -aw $LOCAL)\" \"$(wslpath -aw $REMOTE)\"
</code>```

答:
Check if this configuration might work in your case:

I managed to get it working using the built-in wslpath command which comes with new WSL versions!

My git config on WSL linux side:

```<code>difftool.bc3.cmd=BComp.exe "$(wslpath -aw $LOCAL)" "$(wslpath -aw $REMOTE)"
mergetool.bc3.cmd=BComp.exe "$(wslpath -aw $LOCAL)" "$(wslpath -aw $REMOTE)" "$(wslpath -aw $BASE)" "$(wslpath -aw $MERGED)"
</code>```

BComp.exe is in my $PATH.

I'm using WSL2 on Windows version 2004 (build 19041), and this works both inside the WSL filesystem and also for the mounted Windows filesystem.

The new wslpath -aw converts the Linux paths like this:

```<code>$ wslpath -aw /home/
\\wsl$\Debian\home
</code>```

And Windows paths like this:

```<code>$ wslpath -aw /mnt/c/Users/
C:\Users
</code>```

This makes them both work perfectly with the Windows version of BC when launched from Linux.

Body:
Trying to get git and Beyond Compare to place nicely together on WSL.  Here is the output from git config --list:

diff.tool=bc3
difftool.prompt=false
difftool.bc3.path=/mnt/c/Program Files/Beyond Compare 4/BComp.exe
merge.tool=bc3
mergetool.prompt=false
mergetool.bc3.trustexitcode=true
mergetool.bc3.path=/mnt/c/Program Files/Beyond Compare 4/BComp.exe

Here is my ~/.gitconfig:

[diff]
    tool = bc3
[difftool]
    prompt = false
[difftool "bc3"]
    path = /mnt/c/Program Files/Beyond Compare 4/BComp.exe
[merge]
    tool = bc3
[mergetool]
    prompt = false
[mergetool "bc3"]
    trustExitCode = true
    path = /mnt/c/Program Files/Beyond Compare 4/BComp.exe

my git --version is:

git version 2.25.1

When I try git difftool file_in_git_repo
Beyond Compare opens with the current version in the left pane, but nothing in the right pane (I have confirmed the file exists in the git repo.)

.git/config has no entries referencing diff or merge

Any suggestions would be most welcome

========================================================================

Similar to VonC's suggestion, I was able to get it working with this in my .gitconfig file (disclaimer - I have not used the mergetool with this new method):

[diff]
    tool = bc3
[difftool]
    prompt = false
[difftool "bc3"]
    cmd = '/mnt/c/Program Files/Beyond Compare 4/BComp.exe'   \"$(wslpath -aw $LOCAL)\" \"$(wslpath -aw $REMOTE)\"
[merge]
    tool = bc3
[mergetool]
    prompt = false
[mergetool "bc3"]
    trustExitCode = true
    cmd = '/mnt/c/Program Files/Beyond Compare 4/BComp.exe'   \"$(wslpath -aw $LOCAL)\" \"$(wslpath -aw $REMOTE)\"

Body:
Check if this configuration might work in your case:

I managed to get it working using the built-in wslpath command which comes with new WSL versions!

My git config on WSL linux side:

difftool.bc3.cmd=BComp.exe "$(wslpath -aw $LOCAL)" "$(wslpath -aw $REMOTE)"
mergetool.bc3.cmd=BComp.exe "$(wslpath -aw $LOCAL)" "$(wslpath -aw $REMOTE)" "$(wslpath -aw $BASE)" "$(wslpath -aw $MERGED)"

BComp.exe is in my $PATH.

I'm using WSL2 on Windows version 2004 (build 19041), and this works both inside the WSL filesystem and also for the mounted Windows filesystem.

The new wslpath -aw converts the Linux paths like this:

$ wslpath -aw /home/
\\wsl$\Debian\home

And Windows paths like this:

$ wslpath -aw /mnt/c/Users/
C:\Users

This makes them both work perfectly with the Windows version of BC when launched from Linux.


问:
Scraping this page with Python
I'm trying to scrape the tables that you get from this page after selecting a specific date (ex: jan 2015 to fev 2022) - http://vital.minambiente.gov.co/SILPA_UT_PRE/RUIA/ConsultarSancion.aspx?Ubic=ext

When I tried Selenium, I had trouble finding how to click on the pages (1, 2, 3, 4, 5...) at the bottom so it would send me to the next table.

I'm trying this:

```<code>driver.find_element(By.XPATH, 'href="javascript:__doPostBack(\'ctl00$ContentPlaceHolder1$grdSanciones\',\'Page$1\')"').click()
</code>```

But I get an error: InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$grdSanciones','Page$1')" because of the following error:
TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type.

How would you do that?
Thanks!

答:
That's a pretty nasty attribute value to search on due to the nested quotes. It also looks like something that might change frequently.

A better approach might be to use CSS selectors. .GridPager a will select all of those links, for example. And if you keep track of the page you're on you can find the "next" page link based on that.

Beyond page 10 it mostly just loops, though there is an extra ... link back that we need to account for. This is really a double pagination: pages 1 – 10, then pages 11 – 20, etc.

So something like this:

```<code>page = 1
offset = 0  # For the "..." back-a-page-of-pages link
navigation_links = driver.find_elements(By.CSS_SELECTOR, ".GridPager a")

for link in navigation_links:
    # Do whatever you want with the data on the current page

    # Next page
    navigation_links[(page % 10) - 1 + offset].click()

    page += 1
    offset = 1 if page > 10 else 0
</code>```

Title: Scraping this page with Python

Body:
I'm trying to scrape the tables that you get from this page after selecting a specific date (ex: jan 2015 to fev 2022) - http://vital.minambiente.gov.co/SILPA_UT_PRE/RUIA/ConsultarSancion.aspx?Ubic=ext

When I tried Selenium, I had trouble finding how to click on the pages (1, 2, 3, 4, 5...) at the bottom so it would send me to the next table.

I'm trying this:

driver.find_element(By.XPATH, 'href="javascript:__doPostBack(\'ctl00$ContentPlaceHolder1$grdSanciones\',\'Page$1\')"').click()

But I get an error: InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$grdSanciones','Page$1')" because of the following error:
TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type.

How would you do that?
Thanks!

Body:
That's a pretty nasty attribute value to search on due to the nested quotes. It also looks like something that might change frequently.

A better approach might be to use CSS selectors. .GridPager a will select all of those links, for example. And if you keep track of the page you're on you can find the "next" page link based on that.

Beyond page 10 it mostly just loops, though there is an extra ... link back that we need to account for. This is really a double pagination: pages 1 – 10, then pages 11 – 20, etc.

So something like this:

page = 1
offset = 0  # For the "..." back-a-page-of-pages link
navigation_links = driver.find_elements(By.CSS_SELECTOR, ".GridPager a")

for link in navigation_links:
    # Do whatever you want with the data on the current page

    # Next page
    navigation_links[(page % 10) - 1 + offset].click()

    page += 1
    offset = 1 if page > 10 else 0


问:
How to assign svn command output to a variable in groovy script
So I have a groovy script like this-

```<code>def BRANCH_REV = sh script: "svn info \$url | grep 'Last Changed Rev' | awk '{ print \$4; }'", returnStdout: true , trim: true

println "ccsmp - downstream testing for: $BRANCH_REV"
</code>```

This script is suppose to fetch the last revision number and put that value in a variable called "BRANCH_REV" and second line is suppose to print it.
But I keep getting null value, my console output looks like this-

```<code>[branches%2Ffeatures%2Fcre40_jenkins] Running shell script
+ svn info
+ grep 'Last Changed Rev'
+ awk '{ print $4; }'
23401               <-- It is printing the revision number here

[Pipeline] echo
ccsmp - downstream testing for: 0      <-- but when I try to print the $BRANCH_REV, it prints out 0

[Pipeline] sh
[branches%2Ffeatures%2Fcre40_jenkins] Running shell script
+ echo 0
0                                    <-- same thing happens when I try to echo $BRANCH_REV
</code>```

答:
Solution

If your script is in a Jenkinsfile and your pipeline is configured to checkout that Jenkinsfile ( IE the Jenkinsfile is stored with your code ) you can simply do the following:

```<code>def BRANCH_REV = "r${SVN_REVISION}"
echo "Revision is ${BRANCH_REV}"
</code>```

Body:
So I have a groovy script like this-

def BRANCH_REV = sh script: "svn info \$url | grep 'Last Changed Rev' | awk '{ print \$4; }'", returnStdout: true , trim: true

println "ccsmp - downstream testing for: $BRANCH_REV"

This script is suppose to fetch the last revision number and put that value in a variable called "BRANCH_REV" and second line is suppose to print it.
But I keep getting null value, my console output looks like this-

[branches%2Ffeatures%2Fcre40_jenkins] Running shell script
+ svn info
+ grep 'Last Changed Rev'
+ awk '{ print $4; }'
23401               <-- It is printing the revision number here

[Pipeline] echo
ccsmp - downstream testing for: 0      <-- but when I try to print the $BRANCH_REV, it prints out 0

[Pipeline] sh
[branches%2Ffeatures%2Fcre40_jenkins] Running shell script
+ echo 0
0                                    <-- same thing happens when I try to echo $BRANCH_REV

Body:
Solution

If your script is in a Jenkinsfile and your pipeline is configured to checkout that Jenkinsfile ( IE the Jenkinsfile is stored with your code ) you can simply do the following:

def BRANCH_REV = "r${SVN_REVISION}"
echo "Revision is ${BRANCH_REV}"


问:
increasing width of figure in matplotlib according to number of x values
I was trying to draw a barchart using matplotlib.The number of items to be plotted can vary . I cannot set the figure.set_size_inches(w,h) or set_figwidth(w) with  constants(like 6.,8. or 8.,12. etc),since I cannot tell in advance what the value of w or h should be.I want the width of figure to increase as the number of items to be plotted increases.Can someone tell me how I can do this?

```<code>import pylab

def create_barchart(map):
    xvaluenames = map.keys()
    xvaluenames.sort()
    yvalues = map.values()
    max_yvalue = get_max_yvalue(yvalues)
    xdata = range(len(xvaluenames))
    ydata = [map[x] for x in xvaluenames]
    splitxdata = [x.split('-',1) for x in xvaluenames]
    xlabels = [x[0] for x in splitxdata]
    figure = pylab.figure()
    ax = figure.add_subplot(1,1,1)
    figsize = figure.get_size_inches()
    print 'figure size1=',figsize,'width=',figsize[0],'height=',figsize[1]
    barwidth = .25
    ystep =  max_yvalue/5
    pylab.grid(True)
    if xdata and ydata:
        ax.bar(xdata, ydata, width=barwidth,align='center',color='orange')
        ax.set_xlabel('xvalues',color='green')
        ax.set_ylabel('yvalues',color='green')
        ax.set_xticks(xdata)
        ax.set_xlim([min(xdata) - 0.5, max(xdata) + 0.5])
        ax.set_xticklabels(xlabels)
        ax.set_yticks(range(0,max_yvalue+ystep,ystep))
        ax.set_ylim(0,max(ydata)+ystep)
    figure.autofmt_xdate(rotation=30)
    figure.savefig('mybarplot',format="png")
    print 'figure size2=',figure.get_size_inches()
    pylab.show()

def get_max_yvalue(yvals):
    return max(yvals) if yvals else 0
</code>```

if I try with a small set of items,I get

```<code>if __name__=='__main__':
    datamap = dict(mark=39,jim=40, simon=20,dan=33)
    print datamap
    create_barchart(datamap)
</code>```

but if I use a larger set

```<code>datamap = dict(mark=39,jim=40, simon=20,dan=33)
additional_values= dict(jon=34,ray=23,bert=45,kevin=35,ned=31,bran=11,tywin=56,tyrion=30,jaime=36,griffin=25,viserys=25)
datamap.update(additional_values)
create_barchart(datamap)
</code>```

This looks awful,
I am wondering if there is a way to increase the width of figure,according to the number of items to be plotted,keeping the width of bars in both cases same

答:
You can set the width when you initialize the figure:

```<code># default scale is 1 in your original case, scales with other cases:
widthscale = len(yvalues)/4
figsize = (8*widthscale,6) # fig size in inches (width,height)
figure = pylab.figure(figsize = figsize) # set the figsize
</code>```

Replace the figure = pylab.figure() line with the above three lines and you get what your asking for.

Body:
I was trying to draw a barchart using matplotlib.The number of items to be plotted can vary . I cannot set the figure.set_size_inches(w,h) or set_figwidth(w) with  constants(like 6.,8. or 8.,12. etc),since I cannot tell in advance what the value of w or h should be.I want the width of figure to increase as the number of items to be plotted increases.Can someone tell me how I can do this?

import pylab

def create_barchart(map):
    xvaluenames = map.keys()
    xvaluenames.sort()
    yvalues = map.values()
    max_yvalue = get_max_yvalue(yvalues)
    xdata = range(len(xvaluenames))
    ydata = [map[x] for x in xvaluenames]
    splitxdata = [x.split('-',1) for x in xvaluenames]
    xlabels = [x[0] for x in splitxdata]
    figure = pylab.figure()
    ax = figure.add_subplot(1,1,1)
    figsize = figure.get_size_inches()
    print 'figure size1=',figsize,'width=',figsize[0],'height=',figsize[1]
    barwidth = .25
    ystep =  max_yvalue/5
    pylab.grid(True)
    if xdata and ydata:
        ax.bar(xdata, ydata, width=barwidth,align='center',color='orange')
        ax.set_xlabel('xvalues',color='green')
        ax.set_ylabel('yvalues',color='green')
        ax.set_xticks(xdata)
        ax.set_xlim([min(xdata) - 0.5, max(xdata) + 0.5])
        ax.set_xticklabels(xlabels)
        ax.set_yticks(range(0,max_yvalue+ystep,ystep))
        ax.set_ylim(0,max(ydata)+ystep)
    figure.autofmt_xdate(rotation=30)
    figure.savefig('mybarplot',format="png")
    print 'figure size2=',figure.get_size_inches()
    pylab.show()

def get_max_yvalue(yvals):
    return max(yvals) if yvals else 0

if I try with a small set of items,I get

if __name__=='__main__':
    datamap = dict(mark=39,jim=40, simon=20,dan=33)
    print datamap
    create_barchart(datamap)

but if I use a larger set

datamap = dict(mark=39,jim=40, simon=20,dan=33)
additional_values= dict(jon=34,ray=23,bert=45,kevin=35,ned=31,bran=11,tywin=56,tyrion=30,jaime=36,griffin=25,viserys=25)
datamap.update(additional_values)
create_barchart(datamap)

This looks awful,
I am wondering if there is a way to increase the width of figure,according to the number of items to be plotted,keeping the width of bars in both cases same

Body:
You can set the width when you initialize the figure:

# default scale is 1 in your original case, scales with other cases:
widthscale = len(yvalues)/4
figsize = (8*widthscale,6) # fig size in inches (width,height)
figure = pylab.figure(figsize = figsize) # set the figsize

Replace the figure = pylab.figure() line with the above three lines and you get what your asking for.


问:
Vaadin formlayout won't centre
I'm building a registration form in Vaadin 22 and I want the FormLayout to be in the centre of the page horizontally.

The headlingLabel centres correctly but the form is always to the left hand side of the page.
If I remove the setMaxWidth of the form the form fills the full width of the page.

package dev.onepub.ui.views.authed;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.formlayout.FormLayout.ResponsiveStep;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;

import dev.onepub.dao.DaoMember;
import dev.onepub.entity.enums.ActionEnum;
import dev.onepub.session.MemberSession;
import dev.onepub.ui.DefaultView;
import dev.onepub.ui.OnePubLayout;
import dev.onepub.ui.crud.Access;

/// Place holder for the re-registration process.

@Access(required = ActionEnum.notRequired)
@Route(value = "Register", layout = OnePubLayout.class)
public class RegistrationView extends VerticalLayout
{
    private transient Logger logger = LogManager.getLogger();

    private static final long serialVersionUID = 1L;
    public static final String NAME = "Register";
    public static final String LABEL = "register";

    TextField firstName = new TextField("First name");
    TextField lastName = new TextField("Last name");
    TextField email = new TextField("Preferred Email");
    TextField publisher = new TextField("Organisation Name");

    Checkbox subscribe = new Checkbox("Subscribe to periodic newsletters for product features, tips and tricks.");
    Checkbox terms = new Checkbox();

    Button signup = new Button("Signup");

    private Binder<Registration> binder = new Binder<>(Registration.class);

    public RegistrationView()
    {

        this.setSizeFull();
        // this.setMargin(false);

        HorizontalLayout heading = new HorizontalLayout();
        heading.setWidth("100%");
        Label headingLabel = new Label("Please confirm the following details");
        this.add(headingLabel);

        final var form = new FormLayout();
        this.add(form);
        this.setAlignItems(Alignment.CENTER);
        this.setJustifyContentMode(JustifyContentMode.START);
        form.setMaxWidth("800px");

        terms.setLabelAsHtml(
                "I agree to both the terms and conditions, and the privacy policy.");

        form.add(firstName, lastName, email, publisher, subscribe, terms, signup);
        form.setColspan(email, 2);
        form.setColspan(publisher, 2);
        form.setColspan(subscribe, 2);
        form.setColspan(terms, 2);
        form.setColspan(signup, 2);

        form.setResponsiveSteps(
                // Use one column by default
                new ResponsiveStep("0", 1),
                // Use two columns, if layout's width exceeds 500px
                new ResponsiveStep("500px", 2));

        binder.bindInstanceFields(this);

        final var member = MemberSession.getCurrent().loggedInMember;

        final var registration = new Registration(member);
        binder.setBean(registration);

        signup.addClickListener(event -> save());

    }

    private void save()
    {
        Registration registration = binder.getBean();
        final var member = new DaoMember().findByEntity(MemberSession.getCurrent().loggedInMember);
        member.setFirstname(registration.firstName);
        member.setSurname(registration.lastName);
        member.setPreferredEmail(registration.email);
        member.getPublisher().setName(registration.publisher);
        member.setAcceptedTerms(terms.getValue());
        member.setSubcribed(subscribe.getValue());

        UI.getCurrent().navigate(DefaultView.class);

    }

}
```

答:
Based on @styl3r response I found that I just need to add

```<code>setAlignSelf(Alignment.CENTER, form);
setJustifyContentMode(JustifyContentMode.START);
</code>```

This avoids directly playing with styles.

So the full answer is:

```<code>package dev.onepub.ui.views.authed;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.formlayout.FormLayout.ResponsiveStep;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;

import dev.onepub.dao.DaoMember;
import dev.onepub.entity.enums.ActionEnum;
import dev.onepub.fields.validators.EmailValidator;
import dev.onepub.session.MemberSession;
import dev.onepub.ui.CheckboxWithError;
import dev.onepub.ui.DefaultView;
import dev.onepub.ui.OnePubLayout;
import dev.onepub.ui.crud.Access;
import dev.onepub.ui.crud.PublicView;

/// Place holder for the re-registration process.

@Access(required = ActionEnum.notRequired)
@Route(value = "Register", layout = OnePubLayout.class)
public class RegistrationView extends VerticalLayout implements PublicView
{
    @SuppressWarnings("unused")
    private transient Logger logger = LogManager.getLogger();

    private static final long serialVersionUID = 1L;
    public static final String NAME = "Register";
    public static final String LABEL = "register";

    TextField firstName = new TextField("First name");
    TextField lastName = new TextField("Last name");
    TextField email = new TextField("Preferred Email");
    TextField publisher = new TextField("Organisation Name");

    Checkbox subscribe = new Checkbox(
            "Subscribe to periodic newsletters for product features, tips and tricks. (No more than once a month)");
    CheckboxWithError terms = new CheckboxWithError();

    Button signup = new Button("Signup");

    private Binder<Registration> binder = new Binder<>(Registration.class);

    public RegistrationView()
    {
        this.setSizeFull();
        // this.setMargin(false);

        HorizontalLayout heading = new HorizontalLayout();
        heading.setWidth("100%");
        Label headingLabel = new Label("Please confirm the following details");
        this.add(headingLabel);

        final var form = new FormLayout();
        setAlignSelf(Alignment.CENTER, form);
        setJustifyContentMode(JustifyContentMode.START);
        this.add(form);
        this.setAlignItems(Alignment.CENTER);
        this.setJustifyContentMode(JustifyContentMode.START);
        form.setMaxWidth("800px");

        terms.setLabelAsHtml(
                "I agree to both the <a href='https://www.onepub.dev/terms' target='_blank'>terms and conditions</a>, and the <a href='https://www.onepub.dev/privacy' target='_blank'>privacy policy.</a>");

        form.add(firstName, lastName, email, publisher, subscribe, terms, signup);
        form.setColspan(email, 2);
        form.setColspan(publisher, 2);
        form.setColspan(subscribe, 2);
        form.setColspan(terms, 2);
        form.setColspan(signup, 2);

        form.setResponsiveSteps(
                // Use one column by default
                new ResponsiveStep("0", 1),
                // Use two columns, if layout's width exceeds 500px
                new ResponsiveStep("500px", 2));

        binder.bindInstanceFields(this);

        binder.forField(email).withValidator(new EmailValidator("Note a valid email address"))
                .bind("email");
        binder.forField(terms).withValidator((v) -> v == true, "You must accept the Terms and Conditions")
                .bind("terms");

        final var member = MemberSession.getCurrent().preRegistrationMember;

        final var registration = new Registration(member);
        binder.setBean(registration);

        signup.addClickListener(event -> save());

    }

    private void save()
    {
        Registration registration = binder.getBean();
        final var status = binder.validate();
        if (status.isOk())
        {
            final var member = new DaoMember().findByEntity(MemberSession.getCurrent().loggedInMember);
            member.setFirstname(registration.firstName);
            member.setSurname(registration.lastName);
            member.setPreferredEmail(registration.email);
            member.getPublisher().setName(registration.publisher);
            member.setSubcribed(subscribe.getValue());

            member.setAcceptedTerms(terms.getValue());

            MemberSession.getCurrent().preRegistrationMember = null;

            UI.getCurrent().navigate(DefaultView.class);
        }

    }

}
</code>```

Title: Vaadin formlayout won't centre

Body:
Based on @styl3r response I found that I just need to add

setAlignSelf(Alignment.CENTER, form);
setJustifyContentMode(JustifyContentMode.START);

This avoids directly playing with styles.

So the full answer is:

package dev.onepub.ui.views.authed;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.formlayout.FormLayout.ResponsiveStep;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;

import dev.onepub.dao.DaoMember;
import dev.onepub.entity.enums.ActionEnum;
import dev.onepub.fields.validators.EmailValidator;
import dev.onepub.session.MemberSession;
import dev.onepub.ui.CheckboxWithError;
import dev.onepub.ui.DefaultView;
import dev.onepub.ui.OnePubLayout;
import dev.onepub.ui.crud.Access;
import dev.onepub.ui.crud.PublicView;

/// Place holder for the re-registration process.

@Access(required = ActionEnum.notRequired)
@Route(value = "Register", layout = OnePubLayout.class)
public class RegistrationView extends VerticalLayout implements PublicView
{
    @SuppressWarnings("unused")
    private transient Logger logger = LogManager.getLogger();

    private static final long serialVersionUID = 1L;
    public static final String NAME = "Register";
    public static final String LABEL = "register";

    TextField firstName = new TextField("First name");
    TextField lastName = new TextField("Last name");
    TextField email = new TextField("Preferred Email");
    TextField publisher = new TextField("Organisation Name");

    Checkbox subscribe = new Checkbox(
            "Subscribe to periodic newsletters for product features, tips and tricks. (No more than once a month)");
    CheckboxWithError terms = new CheckboxWithError();

    Button signup = new Button("Signup");

    private Binder<Registration> binder = new Binder<>(Registration.class);

    public RegistrationView()
    {
        this.setSizeFull();
        // this.setMargin(false);

        HorizontalLayout heading = new HorizontalLayout();
        heading.setWidth("100%");
        Label headingLabel = new Label("Please confirm the following details");
        this.add(headingLabel);

        final var form = new FormLayout();
        setAlignSelf(Alignment.CENTER, form);
        setJustifyContentMode(JustifyContentMode.START);
        this.add(form);
        this.setAlignItems(Alignment.CENTER);
        this.setJustifyContentMode(JustifyContentMode.START);
        form.setMaxWidth("800px");

        terms.setLabelAsHtml(
                "I agree to both the <a href='https://www.onepub.dev/terms' target='_blank'>terms and conditions</a>, and the <a href='https://www.onepub.dev/privacy' target='_blank'>privacy policy.</a>");

        form.add(firstName, lastName, email, publisher, subscribe, terms, signup);
        form.setColspan(email, 2);
        form.setColspan(publisher, 2);
        form.setColspan(subscribe, 2);
        form.setColspan(terms, 2);
        form.setColspan(signup, 2);

        form.setResponsiveSteps(
                // Use one column by default
                new ResponsiveStep("0", 1),
                // Use two columns, if layout's width exceeds 500px
                new ResponsiveStep("500px", 2));

        binder.bindInstanceFields(this);

        binder.forField(email).withValidator(new EmailValidator("Note a valid email address"))
                .bind("email");
        binder.forField(terms).withValidator((v) -> v == true, "You must accept the Terms and Conditions")
                .bind("terms");

        final var member = MemberSession.getCurrent().preRegistrationMember;

        final var registration = new Registration(member);
        binder.setBean(registration);

        signup.addClickListener(event -> save());

    }

    private void save()
    {
        Registration registration = binder.getBean();
        final var status = binder.validate();
        if (status.isOk())
        {
            final var member = new DaoMember().findByEntity(MemberSession.getCurrent().loggedInMember);
            member.setFirstname(registration.firstName);
            member.setSurname(registration.lastName);
            member.setPreferredEmail(registration.email);
            member.getPublisher().setName(registration.publisher);
            member.setSubcribed(subscribe.getValue());

            member.setAcceptedTerms(terms.getValue());

            MemberSession.getCurrent().preRegistrationMember = null;

            UI.getCurrent().navigate(DefaultView.class);
        }

    }

}


问:
How to split a code cell in Google Colab?
Using Jupyter Notebook I found that the function to split cells is very useful.
I would like to do that in Google Colab as well, but I can't find how to do it.

Can it be done? And if the answer is yes, how?

答:
If you go to:

```<code>google colab page menu -> Tools -> Keyboard shortcuts -> Split at Cursor
</code>```

you can find it.

The default is Ctrl + M -, But you can modify it to whatever shortcut you prefer.

Body:
If you go to:

google colab page menu -> Tools -> Keyboard shortcuts -> Split at Cursor

you can find it.

The default is Ctrl + M -, But you can modify it to whatever shortcut you prefer.


问:
Converting a list of strings into a nested list of floats and strings skipping the first item
I want to convert a certain list of strings into separated lists inside another list, which will contain strings and floats.
I've tried to use the append method to get the result, but I'm having trouble on making the nested list. Is there a way to get only the last line of my output as the result? This is my code:

```<code>def func(L):
    n = []
    lists = [i.split(',') for i in L]
    for xlist in lists:
        xlist[1:] = [float(item) for item in xlist[1:]]
        n.append(xlist)
        print(n)

if __name__ == '__main__':
    func(['PersonX, 10, 92, 70', 'PersonY, 60, 70', 'PersonZ, 98.5, 1100, 95.5, 38'])

OUTPUT: [['PersonX', 10.0, 92.0, 70.0]]
        [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0]]
        [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]

EXPECTED OUTPUT: [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]
</code>```

Thanks in advance for any help.

答:
We can use some list unpacking and list concatenation to accomplish the result you are looking for:</p>
```<code>def func(L):
    n = []
    for value in L:
        a, *b = value.split(',')
        n.append([a] + [float(item) for item in b])
    print(n)
</code>```

Body:
I want to convert a certain list of strings into separated lists inside another list, which will contain strings and floats.
I've tried to use the append method to get the result, but I'm having trouble on making the nested list. Is there a way to get only the last line of my output as the result? This is my code:

def func(L):
    n = []
    lists = [i.split(',') for i in L]
    for xlist in lists:
        xlist[1:] = [float(item) for item in xlist[1:]]
        n.append(xlist)
        print(n)

if __name__ == '__main__':
    func(['PersonX, 10, 92, 70', 'PersonY, 60, 70', 'PersonZ, 98.5, 1100, 95.5, 38'])

OUTPUT: [['PersonX', 10.0, 92.0, 70.0]]
        [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0]]
        [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]

EXPECTED OUTPUT: [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]

Thanks in advance for any help.

Body:
We can use some list unpacking and list concatenation to accomplish the result you are looking for:

def func(L):
    n = []
    for value in L:
        a, *b = value.split(',')
        n.append([a] + [float(item) for item in b])
    print(n)


问:
Pycord Slash commands, How do you set guild_ids too all guilds bot is in
In Pycord when creating a slash command you need to tell it what servers it can be used in. You do this by adding a argument called guild_ids.

But how would I put a list of guild ids for all the servers my bot is in? I've tried multiple methods but unless I set the guild_ids manually it won't let other servers use them.

It would also have to update every few seconds in case someone invites it too a new server.

答: There is a thing called "global slash commands". If you check the Pycord docs for the slash command, you'll find that the guild_ids parameter is optional, i.e. you can simply omit the guild_ids parameter. If no guild ids are provided, the command will be created globally and be available on every server the bot is in (provided the bot has been granted the applications.commands scope on invite). Note that it may take up to an hour before a global slash command is synchronized to all servers


问:
XML-RPC returning value before executing all function code
I have XML-RPC server:

```<code>import time

import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer

class Worker(object):
    def start_work(self):
        # is it possible do return value to client here?
        self.do_work()
        return 'we started!'

    def do_work(self):
        while(True):
            print 'I\'m doing work...'
            time.sleep(3)

if __name__ == '__main__':
    port = 8080
    server = SimpleXMLRPCServer(("localhost", port))
    print "Listening on port %s..." % port

    w = Worker()

    server.register_function(w.start_work)
    while(1):
        server.handle_request()

# vim: filetype=python syntax=python expandtab shiftwidth=4 softtabstop=4 encoding=utf8
</code>```

And easy client:

```<code>import xmlrpclib
c = xmlrpclib.ServerProxy('http://localhost:8080/')
print c.start_work()
</code>```

Of course value returned by start_work function will be never printed.

My question is how to rewrite server code to make possible returning value before finishing work. I know that I can use threads for that but I want to be sure that there is no easier way.

答:
I'm not sure this is a good idea to do such a thing without threads or without reimplement some parts of the SimpleXMLRPCServer or without breaking XMLRPC protocol, however you can get an early answer by using a yield statement in your called method :

```<code>class Worker(object):
    def start_work(self):
        # is it possible do return value to client here?
        # yes, with a yield
        yield "the_return_value"
        self.do_work()
        # but yielding a first value and returning it to client will disable any next response
        # return 'we started!'

    def do_work(self):
        while(True):
            print 'I\'m doing work...'
            time.sleep(3)
</code>```

And overriding the do_POST method of the SimpleXMLRPCRequestHandler to call twice the called method (everything around the ### parts are the standard part of python code)

```<code>class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):

    def do_POST(self):
        """Handles the HTTP POST request.
        Attempts to interpret all HTTP POST requests as XML-RPC calls,
        which are forwarded to the server's _dispatch method for handling.
        """
        # Check that the path is legal
        if not self.is_rpc_path_valid():
            self.report_404()
            return

        try:
            # Get arguments by reading body of request.
            # We read this in chunks to avoid straining
            # socket.read(); around the 10 or 15Mb mark, some platforms
            # begin to have problems (bug #792570).
            max_chunk_size = 10*1024*1024
            size_remaining = int(self.headers["content-length"])
            L = []
            while size_remaining:
                chunk_size = min(size_remaining, max_chunk_size)
                L.append(self.rfile.read(chunk_size))
                size_remaining -= len(L[-1])
            data = ''.join(L)

            # In previous versions of SimpleXMLRPCServer, _dispatch
            # could be overridden in this class, instead of in
            # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
            # check to see if a subclass implements _dispatch and dispatch
            # using that method if present.
            response = self.server._marshaled_dispatch(
                    data, getattr(self, '_dispatch', None)
                )
            ##############################################
            ##############################################
            ## Here you'll have the first part of your response
            response = response.next() # to get the first item of the generator (yes, a little bit uggly)
            ##############################################
            ##############################################
        except Exception, e: # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            self.send_response(500)

            # Send information about the exception if requested
            if hasattr(self.server, '_send_traceback_header') and \
                    self.server._send_traceback_header:
                self.send_header("X-exception", str(e))
                self.send_header("X-traceback", traceback.format_exc())

            self.end_headers()
        else:
            # got a valid XML RPC response
            self.send_response(200)
            self.send_header("Content-type", "text/xml")
            self.send_header("Content-length", str(len(response)))
            self.end_headers()
            self.wfile.write(response)

            # shut down the connection
            self.wfile.flush()
            self.connection.shutdown(1)

            ##############################################
            ##############################################
            ## Here you've send the the first part of your response to the client, relaunch the method
            self.server._marshaled_dispatch(
                    data, getattr(self, '_dispatch', None)
            )
            ##############################################
            ##############################################
</code>```

Then, the main will become :

```<code>if __name__ == '__main__':
    port = 8080
    server = SimpleXMLRPCServer(("localhost", port), requestHandler=MySimpleXMLRPCRequestHandler)
    print "Listening on port %s..." % port

    w = Worker()

    server.register_function(w.start_work)
    while(1):
        server.handle_request()
</code>```

Body:
I have XML-RPC server:

import time

import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer

class Worker(object):
    def start_work(self):
        # is it possible do return value to client here?
        self.do_work()
        return 'we started!'

    def do_work(self):
        while(True):
            print 'I\'m doing work...'
            time.sleep(3)

if __name__ == '__main__':
    port = 8080
    server = SimpleXMLRPCServer(("localhost", port))
    print "Listening on port %s..." % port

    w = Worker()

    server.register_function(w.start_work)
    while(1):
        server.handle_request()

# vim: filetype=python syntax=python expandtab shiftwidth=4 softtabstop=4 encoding=utf8

And easy client:

import xmlrpclib
c = xmlrpclib.ServerProxy('http://localhost:8080/')
print c.start_work()

Of course value returned by start_work function will be never printed.

My question is how to rewrite server code to make possible returning value before finishing work. I know that I can use threads for that but I want to be sure that there is no easier way.

Body:
I'm not sure this is a good idea to do such a thing without threads or without reimplement some parts of the SimpleXMLRPCServer or without breaking XMLRPC protocol, however you can get an early answer by using a yield statement in your called method :

class Worker(object):
    def start_work(self):
        # is it possible do return value to client here?
        # yes, with a yield
        yield "the_return_value"
        self.do_work()
        # but yielding a first value and returning it to client will disable any next response
        # return 'we started!'

    def do_work(self):
        while(True):
            print 'I\'m doing work...'
            time.sleep(3)

And overriding the do_POST method of the SimpleXMLRPCRequestHandler to call twice the called method (everything around the ### parts are the standard part of python code)

class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):

    def do_POST(self):
        """Handles the HTTP POST request.
        Attempts to interpret all HTTP POST requests as XML-RPC calls,
        which are forwarded to the server's _dispatch method for handling.
        """
        # Check that the path is legal
        if not self.is_rpc_path_valid():
            self.report_404()
            return

        try:
            # Get arguments by reading body of request.
            # We read this in chunks to avoid straining
            # socket.read(); around the 10 or 15Mb mark, some platforms
            # begin to have problems (bug #792570).
            max_chunk_size = 10*1024*1024
            size_remaining = int(self.headers["content-length"])
            L = []
            while size_remaining:
                chunk_size = min(size_remaining, max_chunk_size)
                L.append(self.rfile.read(chunk_size))
                size_remaining -= len(L[-1])
            data = ''.join(L)

            # In previous versions of SimpleXMLRPCServer, _dispatch
            # could be overridden in this class, instead of in
            # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
            # check to see if a subclass implements _dispatch and dispatch
            # using that method if present.
            response = self.server._marshaled_dispatch(
                    data, getattr(self, '_dispatch', None)
                )
            ##############################################
            ##############################################
            ## Here you'll have the first part of your response
            response = response.next() # to get the first item of the generator (yes, a little bit uggly)
            ##############################################
            ##############################################
        except Exception, e: # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            self.send_response(500)

            # Send information about the exception if requested
            if hasattr(self.server, '_send_traceback_header') and \
                    self.server._send_traceback_header:
                self.send_header("X-exception", str(e))
                self.send_header("X-traceback", traceback.format_exc())

            self.end_headers()
        else:
            # got a valid XML RPC response
            self.send_response(200)
            self.send_header("Content-type", "text/xml")
            self.send_header("Content-length", str(len(response)))
            self.end_headers()
            self.wfile.write(response)

            # shut down the connection
            self.wfile.flush()
            self.connection.shutdown(1)

            ##############################################
            ##############################################
            ## Here you've send the the first part of your response to the client, relaunch the method
            self.server._marshaled_dispatch(
                    data, getattr(self, '_dispatch', None)
            )
            ##############################################
            ##############################################

Then, the main will become :

if __name__ == '__main__':
    port = 8080
    server = SimpleXMLRPCServer(("localhost", port), requestHandler=MySimpleXMLRPCRequestHandler)
    print "Listening on port %s..." % port

    w = Worker()

    server.register_function(w.start_work)
    while(1):
        server.handle_request()


问:
Open / load image as numpy ndarray directly
I used to use scipy which would load an image from file straight into an ndarray.

```<code>from scipy import misc
img = misc.imread('./myimage.jpg')
type(img)
>>> numpy.ndarray
</code>```

But now it gives me a DeprecationWarning and the docs say it will be removed in 1.2.0. and I should use imageio.imread instead. But:

```<code>import imageio
img = imageio.imread('./myimage.jpg')
type(img)
>>> imageio.core.util.Image
</code>```

I could convert it by doing

```<code>img = numpy.array(img)
</code>```

But this seems hacky. Is there any way to load an image straight into a numpy array as I was doing before with scipy's misc.imread (other than using OpenCV)?

答:
If it was a bitmap or even jpeg, you can do:

```<code>import matplotlib.pyplot as plt
import numpy as np
# 'pip install pillow' but import PIL
from PIL import Image

png_filepath = 'somepng.png'
png_pil_img = Image.open(png_filepath)
# this will print info about the PIL object
print(png_pil_img.format, png_pil_img.size, png_pil_img.mode)
png_np_img = np.asarray(png_pil_img)
plt.imshow(png_np_img) # this will graphit in a jupyter notebook
# or if its grayscale plt.imshow(png_np_img, cmap='gray')
# FWIW, this will show the np characteritics
print("shape is ", png_np_img.shape)
print("dtype is ", png_np_img.dtype)
print("ndim is ", png_np_img.ndim)
print("itemsize is ", png_np_img.itemsize) # size in bytes of each array element
print("nbytes is ", png_np_img.nbytes) # size in bytes of each array element
</code>```

If you have a jpg, it works the same. PIL.image will decode the compressed JPG, and convert it to an array for you.  Literally it will do all this for you.  Perhaps you could load the raw bitmap with file io skipping the header, yadda yadda, but PIL is popular for a reason.

The output for a grayscale png will look like this:

```<code>PNG (3024, 4032) L
shape is  (4032, 3024)
dtype is  uint8
ndim is  2
itemsize is  1
nbytes is  12192768
</code>```

The output for a color jpeg will look like this:

```<code>JPEG (704, 480) RGB
shape is  (480, 704, 3)
dtype is  uint8
ndim is  3
itemsize is  1
nbytes is  1013760
</code>```

In either case, the pixel values range 0-255 as ints.  They are not floats.  The color image has three channels corresponding to red green and blue.  The grayscale image is much greater resolution and the jpg.

Body:
I used to use scipy which would load an image from file straight into an ndarray.

from scipy import misc
img = misc.imread('./myimage.jpg')
type(img)
>>> numpy.ndarray

But now it gives me a DeprecationWarning and the docs say it will be removed in 1.2.0. and I should use imageio.imread instead. But:

import imageio
img = imageio.imread('./myimage.jpg')
type(img)
>>> imageio.core.util.Image

I could convert it by doing

img = numpy.array(img)

But this seems hacky. Is there any way to load an image straight into a numpy array as I was doing before with scipy's misc.imread (other than using OpenCV)?

Body:
If it was a bitmap or even jpeg, you can do:

import matplotlib.pyplot as plt
import numpy as np
# 'pip install pillow' but import PIL
from PIL import Image

png_filepath = 'somepng.png'
png_pil_img = Image.open(png_filepath)
# this will print info about the PIL object
print(png_pil_img.format, png_pil_img.size, png_pil_img.mode)
png_np_img = np.asarray(png_pil_img)
plt.imshow(png_np_img) # this will graphit in a jupyter notebook
# or if its grayscale plt.imshow(png_np_img, cmap='gray')
# FWIW, this will show the np characteritics
print("shape is ", png_np_img.shape)
print("dtype is ", png_np_img.dtype)
print("ndim is ", png_np_img.ndim)
print("itemsize is ", png_np_img.itemsize) # size in bytes of each array element
print("nbytes is ", png_np_img.nbytes) # size in bytes of each array element

If you have a jpg, it works the same. PIL.image will decode the compressed JPG, and convert it to an array for you.  Literally it will do all this for you.  Perhaps you could load the raw bitmap with file io skipping the header, yadda yadda, but PIL is popular for a reason.

The output for a grayscale png will look like this:

PNG (3024, 4032) L
shape is  (4032, 3024)
dtype is  uint8
ndim is  2
itemsize is  1
nbytes is  12192768

The output for a color jpeg will look like this:

JPEG (704, 480) RGB
shape is  (480, 704, 3)
dtype is  uint8
ndim is  3
itemsize is  1
nbytes is  1013760

In either case, the pixel values range 0-255 as ints.  They are not floats.  The color image has three channels corresponding to red green and blue.  The grayscale image is much greater resolution and the jpg.


问:
Getting current date, time, and day in Laravel
I need to get the current date, time, and day using Laravel.

I tried to echo  $ldate = new DateTime('today'); and $ldate = new DateTime('now');

But it is always returning 1.

How can I get the current date, time, and day?

答:
today data and time

```<code>return now::();
</code>```

time

```<code>return now()->toTimeString();
</code>```

Body:
today data and time

return now::();

time

return now()->toTimeString();


问:
DIV / Form alignment
First let me start off by saying that I am NO web developer. I work more on embedded stuff. I am completely ignorant to the web design standards or common practices. Any help with be much appreciated.

What I am trying to accomplish

To make a form with several rows of checkboxes / drop downs / textboxes that is incredibly simple and intuitive to operate. It has to be compatible fully with IE 6+. Any other browsers are non mandatory (this is an in house solution that will only be viewed on IE).

The thing I have been trying to accomplish is create another column of checkboxes that align like the current set.

Here is what it currently looks like in IE

My code

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<style type="text/css">
.right_div_check_boxes { width:70%;float:right;} <!-- 75% -->
.left_div_input_boxes {width:15%;float:left;}    <!--15%-->

</style>

<div class="left_div_input_boxes" style="position:relative">

    <form>
    <label>Submitted by (First Name)</label>
    <input type="text" style="width:150px" name="firstname" /><br>
    <label>Submitted by (Last Name)</label><br>
    <input type="text" name="lastname"/>
    <label>Employee Number</label><br>
    <input type="text" name="employnum"/>

    <form>
    <label>What</label>
    <select style="width:150px" name="observer">
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    </select>

    <label>Who</label>
    <form action="">
    <select style="width:150px" name="who">
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    </select>

    <label>Operation Code</label>
    <select  style="width:150px"  name="opcode">
                       <option value="other">TEST</option>
                       <option value="other">TEST</option>
                    </select>

                    <label>Center</label>
                    <select style="width:150px" name="cost">

                        <option value="Zone 1"> Zone 1 </option>
                        <option value="Zone 2"> Zone 2 </option>
                        <option value="Zone 3"> Zone 3 </option>
                    </select>
                    </form>

</div>

<div class="right_div_check_boxes" style="position:relative">
<label>Dangers</label>
<form>

<input type="checkbox" name="vehicle" value="Bike" />Line of Fire<br />
<input type="checkbox" name="vehicle" value="Car" />Respirtory Protection<br />
<input type="checkbox" name="vehicle" value="Car" />Ears/Hearing Protection<br />
<input type="checkbox" name="vehicle" value="Car" />Eye/Face Protection<br />
</div>
<br />

</head>
<body>

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

答: Use a table instead of a div. If you need to add more rows, that is at least as simple as adding more rows in this context. Adding another column of checkboxes is also just as easy. Simply add another column to the table.</p>

Title: DIV / Form alignment

Body:
First let me start off by saying that I am NO web developer. I work more on embedded stuff. I am completely ignorant to the web design standards or common practices. Any help with be much appreciated.

What I am trying to accomplish

To make a form with several rows of checkboxes / drop downs / textboxes that is incredibly simple and intuitive to operate. It has to be compatible fully with IE 6+. Any other browsers are non mandatory (this is an in house solution that will only be viewed on IE).

The thing I have been trying to accomplish is create another column of checkboxes that align like the current set.

Here is what it currently looks like in IE

My code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

    <form>
    Submitted by (First Name)
    <input type="text" style="width:150px" name="firstname" />

    Submitted by (Last Name)

    <input type="text" name="lastname"/>
    Employee Number

    <input type="text" name="employnum"/>

    <form>
    What
    <select style="width:150px" name="observer">
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    </select>

    Who
    <form action="">
    <select style="width:150px" name="who">
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    <option value="other">TEST</option>
    </select>

    Operation Code
    <select  style="width:150px"  name="opcode">
                       <option value="other">TEST</option>
                       <option value="other">TEST</option>
                    </select>

                    Center
                    <select style="width:150px" name="cost">

                        <option value="Zone 1"> Zone 1 </option>
                        <option value="Zone 2"> Zone 2 </option>
                        <option value="Zone 3"> Zone 3 </option>
                    </select>
                    </form>

Dangers
<form>

<input type="checkbox" name="vehicle" value="Bike" />Line of Fire

<input type="checkbox" name="vehicle" value="Car" />Respirtory Protection

<input type="checkbox" name="vehicle" value="Car" />Ears/Hearing Protection

<input type="checkbox" name="vehicle" value="Car" />Eye/Face Protection